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 |
|---|---|---|---|---|---|
Ruby | Ruby | use regular memoization | 386ab893f68ee8344674f7fd2a248dcae9f5d2b0 | <ide><path>actioncable/lib/action_cable/channel/test_case.rb
<ide> def transmit(cable_message)
<ide> end
<ide>
<ide> def connection_identifier
<del> unless defined? @connection_identifier
<del> @connection_identifier = connection_gid identifiers.filter_map { |id| send(id.to_sym) if id }
<del> end
<del>
<del> @connection_identifier
<add> @connection_identifier ||= connection_gid(identifiers.filter_map { |id| send(id.to_sym) if id })
<ide> end
<ide>
<ide> private
<ide> def connection_gid(ids)
<ide> ids.map do |o|
<del> if o.respond_to? :to_gid_param
<add> if o.respond_to?(:to_gid_param)
<ide> o.to_gid_param
<ide> else
<ide> o.to_s | 1 |
Ruby | Ruby | add argv.build_head? and use it | 21c37fbac6b94afd44da4ce0b0fc1599b8165fde | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def quieter?
<ide> def interactive?
<ide> flag? '--interactive'
<ide> end
<add> def build_head?
<add> flag? '--HEAD'
<add> end
<ide>
<ide> def flag? flag
<ide> options.each do |arg| | 1 |
Go | Go | add integration test for volume plugins on swarm | 45990d6e6144daaaf53b09325e7576f0cbec74f3 | <ide><path>integration-cli/daemon/daemon_swarm.go
<ide> func (d *Swarm) GetServiceTasks(c *check.C, service string) []swarm.Task {
<ide> return tasks
<ide> }
<ide>
<del>// CheckServiceRunningTasks returns the number of running tasks for the specified service
<del>func (d *Swarm) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
<add>// CheckServiceTasksInState returns the number of tasks with a matching state,
<add>// and optional message substring.
<add>func (d *Swarm) CheckServiceTasksInState(service string, state swarm.TaskState, message string) func(*check.C) (interface{}, check.CommentInterface) {
<ide> return func(c *check.C) (interface{}, check.CommentInterface) {
<ide> tasks := d.GetServiceTasks(c, service)
<del> var runningCount int
<add> var count int
<ide> for _, task := range tasks {
<del> if task.Status.State == swarm.TaskStateRunning {
<del> runningCount++
<add> if task.Status.State == state {
<add> if message == "" || strings.Contains(task.Status.Message, message) {
<add> count++
<add> }
<ide> }
<ide> }
<del> return runningCount, nil
<add> return count, nil
<ide> }
<ide> }
<ide>
<add>// CheckServiceRunningTasks returns the number of running tasks for the specified service
<add>func (d *Swarm) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
<add> return d.CheckServiceTasksInState(service, swarm.TaskStateRunning, "")
<add>}
<add>
<ide> // CheckServiceUpdateState returns the current update state for the specified service
<ide> func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) {
<ide> return func(c *check.C) (interface{}, check.CommentInterface) {
<ide><path>integration-cli/docker_cli_swarm_unix_test.go
<add>// +build !windows
<add>
<add>package main
<add>
<add>import (
<add> "encoding/json"
<add> "strings"
<add>
<add> "github.com/docker/docker/api/types/swarm"
<add> "github.com/docker/docker/pkg/integration/checker"
<add> "github.com/go-check/check"
<add>)
<add>
<add>func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> out, err := d.Cmd("service", "create", "--mount", "type=volume,source=my-volume,destination=/foo,volume-driver=customvolumedriver", "--name", "top", "busybox", "top")
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> // Make sure task stays pending before plugin is available
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckServiceTasksInState("top", swarm.TaskStatePending, "missing plugin on 1 node"), checker.Equals, 1)
<add>
<add> plugin := newVolumePlugin(c, "customvolumedriver")
<add> defer plugin.Close()
<add>
<add> // create a dummy volume to trigger lazy loading of the plugin
<add> out, err = d.Cmd("volume", "create", "-d", "customvolumedriver", "hello")
<add>
<add> // TODO(aaronl): It will take about 15 seconds for swarm to realize the
<add> // plugin was loaded. Switching the test over to plugin v2 would avoid
<add> // this long delay.
<add>
<add> // make sure task has been deployed.
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
<add>
<add> out, err = d.Cmd("ps", "-q")
<add> c.Assert(err, checker.IsNil)
<add> containerID := strings.TrimSpace(out)
<add>
<add> out, err = d.Cmd("inspect", "-f", "{{json .Mounts}}", containerID)
<add> c.Assert(err, checker.IsNil)
<add>
<add> var mounts []struct {
<add> Name string
<add> Driver string
<add> }
<add>
<add> c.Assert(json.NewDecoder(strings.NewReader(out)).Decode(&mounts), checker.IsNil)
<add> c.Assert(len(mounts), checker.Equals, 1, check.Commentf(out))
<add> c.Assert(mounts[0].Name, checker.Equals, "my-volume")
<add> c.Assert(mounts[0].Driver, checker.Equals, "customvolumedriver")
<add>} | 2 |
Text | Text | remove reading spaces in the code block [ci skip] | 3760cff0676e05404175074bcee89bd8d3a3ed82 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> override it on a per model basis. This should help you migrate all your models t
<ide> associations required by default.
<ide>
<ide> ```ruby
<del> class Book < ApplicationRecord
<del> # model is not yet ready to have its association required by default
<add> class Book < ApplicationRecord
<add> # model is not yet ready to have its association required by default
<ide>
<del> self.belongs_to_required_by_default = false
<del> belongs_to(:author)
<del> end
<add> self.belongs_to_required_by_default = false
<add> belongs_to(:author)
<add> end
<ide>
<del> class Car < ApplicationRecord
<del> # model is ready to have its association required by default
<add> class Car < ApplicationRecord
<add> # model is ready to have its association required by default
<ide>
<del> self.belongs_to_required_by_default = true
<del> belongs_to(:pilot)
<del> end
<add> self.belongs_to_required_by_default = true
<add> belongs_to(:pilot)
<add> end
<ide> ```
<ide>
<ide> #### Per-form CSRF Tokens | 1 |
Text | Text | fix typo in addons.md | aa08cf1e7a44d0899a084f9a94e068d3724e31d6 | <ide><path>doc/api/addons.md
<ide> illustration of how it can be used.
<ide> N-API is an API for building native Addons. It is independent from
<ide> the underlying JavaScript runtime (e.g. V8) and is maintained as part of
<ide> Node.js itself. This API will be Application Binary Interface (ABI) stable
<del>across version of Node.js. It is intended to insulate Addons from
<add>across versions of Node.js. It is intended to insulate Addons from
<ide> changes in the underlying JavaScript engine and allow modules
<ide> compiled for one version to run on later versions of Node.js without
<ide> recompilation. Addons are built/packaged with the same approach/tools | 1 |
Text | Text | add more details to the deployment doc | 6de65faef464e92076936aec5f8dfa705b6529fb | <ide><path>docs/deployment.md
<ide> HTTPS is enabled by default and doesn't require extra configuration.
<ide>
<ide> #### From a git repository
<ide>
<del>You can link your project in [GitHub](https://zeit.co/new), [GitLab](https://zeit.co/new), or [Bitbucket](https://zeit.co/new) through the [web interface](https://zeit.co/new). This will automatically set up deployment previews for pull requests and commits.
<add>You can link your project in [GitHub](https://zeit.co/new), [GitLab](https://zeit.co/new), or [Bitbucket](https://zeit.co/new) through the [web interface](https://zeit.co/new). This will automatically set up deployment previews for pull requests and commits. To learn more about ZEIT Now’s Git integration, take a look at [our documentation here](https://zeit.co/docs/v2/git-integration/).
<ide>
<ide> #### Through the ZEIT Now CLI
<ide>
<del>You can install the command line tool using npm:
<add>You can install [Now CLI](https://zeit.co/download) from either npm or Yarn. Using npm, run the following command from your terminal:
<ide>
<ide> ```bash
<ide> npm install -g now
<ide> now
<ide>
<ide> You will receive a unique link similar to the following: https://your-project.username.now.sh.
<ide>
<add>#### Custom domains
<add>
<add>Once deployed on ZEIT Now, your projects can be assigned to a custom domain of your choice. To learn more, take a look at [our documentation here](https://zeit.co/docs/v2/custom-domains/).
<add>
<ide> ## Self hosting
<ide>
<ide> Next.js can be deployed to any hosting provider that supports Node.js. In order to self-host there are two commands: `next build` and `next start`. | 1 |
Go | Go | move api to it's own package | f556cd4186dfdb5e96b2e58b5caf9edbe7e2d7df | <add><path>api/api.go
<del><path>api.go
<del>package docker
<add>package api
<ide>
<ide> import (
<ide> "bufio"
<ide> const (
<ide> DEFAULTUNIXSOCKET = "/var/run/docker.sock"
<ide> )
<ide>
<del>type HttpApiFunc func(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error
<add>type HttpApiFunc func(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error
<ide>
<ide> func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
<ide> conn, _, err := w.(http.Hijacker).Hijack()
<ide> func getBoolParam(value string) (bool, error) {
<ide> return ret, nil
<ide> }
<ide>
<del>func matchesContentType(contentType, expectedType string) bool {
<add>//TODO remove, used on < 1.5 in getContainersJSON
<add>func displayablePorts(ports *engine.Table) string {
<add> result := []string{}
<add> for _, port := range ports.Data {
<add> if port.Get("IP") == "" {
<add> result = append(result, fmt.Sprintf("%d/%s", port.GetInt("PublicPort"), port.Get("Type")))
<add> } else {
<add> result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.Get("IP"), port.GetInt("PublicPort"), port.GetInt("PrivatePort"), port.Get("Type")))
<add> }
<add> }
<add> return strings.Join(result, ", ")
<add>}
<add>
<add>func MatchesContentType(contentType, expectedType string) bool {
<ide> mimetype, _, err := mime.ParseMediaType(contentType)
<ide> if err != nil {
<ide> utils.Errorf("Error parsing media type: %s error: %s", contentType, err.Error())
<ide> }
<ide> return err == nil && mimetype == expectedType
<ide> }
<ide>
<del>func postAuth(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postAuth(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> var (
<ide> authConfig, err = ioutil.ReadAll(r.Body)
<del> job = srv.Eng.Job("auth")
<add> job = eng.Job("auth")
<ide> status string
<ide> )
<ide> if err != nil {
<ide> func postAuth(srv *Server, version float64, w http.ResponseWriter, r *http.Reque
<ide> return nil
<ide> }
<ide>
<del>func getVersion(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getVersion(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.Header().Set("Content-Type", "application/json")
<del> srv.Eng.ServeHTTP(w, r)
<add> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func postContainersKill(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersKill(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<del> job := srv.Eng.Job("kill", vars["name"])
<add> job := eng.Job("kill", vars["name"])
<ide> if sig := r.Form.Get("signal"); sig != "" {
<ide> job.Args = append(job.Args, sig)
<ide> }
<ide> func postContainersKill(srv *Server, version float64, w http.ResponseWriter, r *
<ide> return nil
<ide> }
<ide>
<del>func getContainersExport(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersExport(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> job := srv.Eng.Job("export", vars["name"])
<add> job := eng.Job("export", vars["name"])
<ide> job.Stdout.Add(w)
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func getImagesJSON(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesJSON(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide>
<ide> var (
<ide> err error
<ide> outs *engine.Table
<del> job = srv.Eng.Job("images")
<add> job = eng.Job("images")
<ide> )
<ide>
<ide> job.Setenv("filter", r.Form.Get("filter"))
<ide> func getImagesJSON(srv *Server, version float64, w http.ResponseWriter, r *http.
<ide> return nil
<ide> }
<ide>
<del>func getImagesViz(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesViz(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if version > 1.6 {
<ide> w.WriteHeader(http.StatusNotFound)
<ide> return fmt.Errorf("This is now implemented in the client.")
<ide> }
<del> srv.Eng.ServeHTTP(w, r)
<add> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func getInfo(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getInfo(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.Header().Set("Content-Type", "application/json")
<del> srv.Eng.ServeHTTP(w, r)
<add> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func getEvents(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getEvents(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide>
<ide> w.Header().Set("Content-Type", "application/json")
<del> var job = srv.Eng.Job("events", r.RemoteAddr)
<add> var job = eng.Job("events", r.RemoteAddr)
<ide> job.Stdout.Add(utils.NewWriteFlusher(w))
<ide> job.Setenv("since", r.Form.Get("since"))
<ide> return job.Run()
<ide> }
<ide>
<del>func getImagesHistory(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesHistory(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> var job = srv.Eng.Job("history", vars["name"])
<add> var job = eng.Job("history", vars["name"])
<ide> job.Stdout.Add(w)
<ide>
<ide> if err := job.Run(); err != nil {
<ide> func getImagesHistory(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> return nil
<ide> }
<ide>
<del>func getContainersChanges(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersChanges(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = srv.Eng.Job("changes", vars["name"])
<add> var job = eng.Job("changes", vars["name"])
<ide> job.Stdout.Add(w)
<ide>
<ide> return job.Run()
<ide> }
<ide>
<del>func getContainersTop(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersTop(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if version < 1.4 {
<ide> return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
<ide> }
<ide> func getContainersTop(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> return err
<ide> }
<ide>
<del> job := srv.Eng.Job("top", vars["name"], r.Form.Get("ps_args"))
<add> job := eng.Job("top", vars["name"], r.Form.Get("ps_args"))
<ide> job.Stdout.Add(w)
<ide> return job.Run()
<ide> }
<ide>
<del>func getContainersJSON(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersJSON(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> var (
<ide> err error
<ide> outs *engine.Table
<del> job = srv.Eng.Job("containers")
<add> job = eng.Job("containers")
<ide> )
<ide>
<ide> job.Setenv("all", r.Form.Get("all"))
<ide> func getContainersJSON(srv *Server, version float64, w http.ResponseWriter, r *h
<ide> return nil
<ide> }
<ide>
<del>func postImagesTag(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesTag(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> job := srv.Eng.Job("tag", vars["name"], r.Form.Get("repo"), r.Form.Get("tag"))
<add> job := eng.Job("tag", vars["name"], r.Form.Get("repo"), r.Form.Get("tag"))
<ide> job.Setenv("force", r.Form.Get("force"))
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> func postImagesTag(srv *Server, version float64, w http.ResponseWriter, r *http.
<ide> return nil
<ide> }
<ide>
<del>func postCommit(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postCommit(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> var (
<ide> config engine.Env
<ide> env engine.Env
<del> job = srv.Eng.Job("commit", r.Form.Get("container"))
<add> job = eng.Job("commit", r.Form.Get("container"))
<ide> )
<ide> if err := config.Import(r.Body); err != nil {
<ide> utils.Errorf("%s", err)
<ide> func postCommit(srv *Server, version float64, w http.ResponseWriter, r *http.Req
<ide> }
<ide>
<ide> // Creates an image from Pull or from Import
<del>func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesCreate(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> metaHeaders[k] = v
<ide> }
<ide> }
<del> job = srv.Eng.Job("pull", r.Form.Get("fromImage"), tag)
<add> job = eng.Job("pull", r.Form.Get("fromImage"), tag)
<ide> job.SetenvBool("parallel", version > 1.3)
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<ide> } else { //import
<del> job = srv.Eng.Job("import", r.Form.Get("fromSrc"), r.Form.Get("repo"), tag)
<add> job = eng.Job("import", r.Form.Get("fromSrc"), r.Form.Get("repo"), tag)
<ide> job.Stdin.Add(r.Body)
<ide> }
<ide>
<ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> return nil
<ide> }
<ide>
<del>func getImagesSearch(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesSearch(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func getImagesSearch(srv *Server, version float64, w http.ResponseWriter, r *htt
<ide> }
<ide> }
<ide>
<del> var job = srv.Eng.Job("search", r.Form.Get("term"))
<add> var job = eng.Job("search", r.Form.Get("term"))
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<ide> job.Stdout.Add(w)
<ide>
<ide> return job.Run()
<ide> }
<ide>
<del>func postImagesInsert(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesInsert(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postImagesInsert(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> w.Header().Set("Content-Type", "application/json")
<ide> }
<ide>
<del> job := srv.Eng.Job("insert", vars["name"], r.Form.Get("url"), r.Form.Get("path"))
<add> job := eng.Job("insert", vars["name"], r.Form.Get("url"), r.Form.Get("path"))
<ide> job.SetenvBool("json", version > 1.0)
<ide> job.Stdout.Add(w)
<ide> if err := job.Run(); err != nil {
<ide> func postImagesInsert(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> return nil
<ide> }
<ide>
<del>func postImagesPush(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesPush(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postImagesPush(srv *Server, version float64, w http.ResponseWriter, r *http
<ide> if version > 1.0 {
<ide> w.Header().Set("Content-Type", "application/json")
<ide> }
<del> job := srv.Eng.Job("push", vars["name"])
<add> job := eng.Job("push", vars["name"])
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<ide> job.SetenvBool("json", version > 1.0)
<ide> func postImagesPush(srv *Server, version float64, w http.ResponseWriter, r *http
<ide> return nil
<ide> }
<ide>
<del>func getImagesGet(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesGet(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> if version > 1.0 {
<ide> w.Header().Set("Content-Type", "application/x-tar")
<ide> }
<del> job := srv.Eng.Job("image_export", vars["name"])
<add> job := eng.Job("image_export", vars["name"])
<ide> job.Stdout.Add(w)
<ide> return job.Run()
<ide> }
<ide>
<del>func postImagesLoad(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> job := srv.Eng.Job("load")
<add>func postImagesLoad(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> job := eng.Job("load")
<ide> job.Stdin.Add(r.Body)
<ide> return job.Run()
<ide> }
<ide>
<del>func postContainersCreate(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersCreate(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return nil
<ide> }
<ide> var (
<ide> out engine.Env
<del> job = srv.Eng.Job("create", r.Form.Get("name"))
<add> job = eng.Job("create", r.Form.Get("name"))
<ide> outWarnings []string
<ide> outId string
<ide> warnings = bytes.NewBuffer(nil)
<ide> func postContainersCreate(srv *Server, version float64, w http.ResponseWriter, r
<ide> return writeJSON(w, http.StatusCreated, out)
<ide> }
<ide>
<del>func postContainersRestart(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersRestart(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> job := srv.Eng.Job("restart", vars["name"])
<add> job := eng.Job("restart", vars["name"])
<ide> job.Setenv("t", r.Form.Get("t"))
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> func postContainersRestart(srv *Server, version float64, w http.ResponseWriter,
<ide> return nil
<ide> }
<ide>
<del>func deleteContainers(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func deleteContainers(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> job := srv.Eng.Job("container_delete", vars["name"])
<add> job := eng.Job("container_delete", vars["name"])
<ide> job.Setenv("removeVolume", r.Form.Get("v"))
<ide> job.Setenv("removeLink", r.Form.Get("link"))
<ide> if err := job.Run(); err != nil {
<ide> func deleteContainers(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide> return nil
<ide> }
<ide>
<del>func deleteImages(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func deleteImages(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = srv.Eng.Job("image_delete", vars["name"])
<add> var job = eng.Job("image_delete", vars["name"])
<ide> job.Stdout.Add(w)
<ide> job.SetenvBool("autoPrune", version > 1.1)
<ide>
<ide> return job.Run()
<ide> }
<ide>
<del>func postContainersStart(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersStart(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> name := vars["name"]
<del> job := srv.Eng.Job("start", name)
<add> job := eng.Job("start", name)
<ide> // allow a nil body for backwards compatibility
<ide> if r.Body != nil {
<del> if matchesContentType(r.Header.Get("Content-Type"), "application/json") {
<add> if MatchesContentType(r.Header.Get("Content-Type"), "application/json") {
<ide> if err := job.DecodeEnv(r.Body); err != nil {
<ide> return err
<ide> }
<ide> func postContainersStart(srv *Server, version float64, w http.ResponseWriter, r
<ide> return nil
<ide> }
<ide>
<del>func postContainersStop(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersStop(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> job := srv.Eng.Job("stop", vars["name"])
<add> job := eng.Job("stop", vars["name"])
<ide> job.Setenv("t", r.Form.Get("t"))
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> func postContainersStop(srv *Server, version float64, w http.ResponseWriter, r *
<ide> return nil
<ide> }
<ide>
<del>func postContainersWait(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersWait(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> var (
<ide> env engine.Env
<ide> status string
<del> job = srv.Eng.Job("wait", vars["name"])
<add> job = eng.Job("wait", vars["name"])
<ide> )
<ide> job.Stdout.AddString(&status)
<ide> if err := job.Run(); err != nil {
<ide> func postContainersWait(srv *Server, version float64, w http.ResponseWriter, r *
<ide> return writeJSON(w, http.StatusOK, env)
<ide> }
<ide>
<del>func postContainersResize(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersResize(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> if err := srv.Eng.Job("resize", vars["name"], r.Form.Get("h"), r.Form.Get("w")).Run(); err != nil {
<add> if err := eng.Job("resize", vars["name"], r.Form.Get("h"), r.Form.Get("w")).Run(); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func postContainersAttach(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersAttach(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postContainersAttach(srv *Server, version float64, w http.ResponseWriter, r
<ide> }
<ide>
<ide> var (
<del> job = srv.Eng.Job("inspect", vars["name"], "container")
<add> job = eng.Job("inspect", vars["name"], "container")
<ide> c, err = job.Stdout.AddEnv()
<ide> )
<ide> if err != nil {
<ide> func postContainersAttach(srv *Server, version float64, w http.ResponseWriter, r
<ide> errStream = outStream
<ide> }
<ide>
<del> job = srv.Eng.Job("attach", vars["name"])
<add> job = eng.Job("attach", vars["name"])
<ide> job.Setenv("logs", r.Form.Get("logs"))
<ide> job.Setenv("stream", r.Form.Get("stream"))
<ide> job.Setenv("stdin", r.Form.Get("stdin"))
<ide> func postContainersAttach(srv *Server, version float64, w http.ResponseWriter, r
<ide> return nil
<ide> }
<ide>
<del>func wsContainersAttach(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func wsContainersAttach(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide>
<del> if err := srv.Eng.Job("inspect", vars["name"], "container").Run(); err != nil {
<add> if err := eng.Job("inspect", vars["name"], "container").Run(); err != nil {
<ide> return err
<ide> }
<ide>
<ide> h := websocket.Handler(func(ws *websocket.Conn) {
<ide> defer ws.Close()
<del> job := srv.Eng.Job("attach", vars["name"])
<add> job := eng.Job("attach", vars["name"])
<ide> job.Setenv("logs", r.Form.Get("logs"))
<ide> job.Setenv("stream", r.Form.Get("stream"))
<ide> job.Setenv("stdin", r.Form.Get("stdin"))
<ide> func wsContainersAttach(srv *Server, version float64, w http.ResponseWriter, r *
<ide> return nil
<ide> }
<ide>
<del>func getContainersByName(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersByName(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = srv.Eng.Job("inspect", vars["name"], "container")
<add> var job = eng.Job("inspect", vars["name"], "container")
<ide> job.Stdout.Add(w)
<ide> job.SetenvBool("conflict", true) //conflict=true to detect conflict between containers and images in the job
<ide> return job.Run()
<ide> }
<ide>
<del>func getImagesByName(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesByName(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = srv.Eng.Job("inspect", vars["name"], "image")
<add> var job = eng.Job("inspect", vars["name"], "image")
<ide> job.Stdout.Add(w)
<ide> job.SetenvBool("conflict", true) //conflict=true to detect conflict between containers and images in the job
<ide> return job.Run()
<ide> }
<ide>
<del>func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postBuild(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if version < 1.3 {
<ide> return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
<ide> }
<ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ
<ide> authConfig = &auth.AuthConfig{}
<ide> configFileEncoded = r.Header.Get("X-Registry-Config")
<ide> configFile = &auth.ConfigFile{}
<del> job = srv.Eng.Job("build")
<add> job = eng.Job("build")
<ide> )
<ide>
<ide> // This block can be removed when API versions prior to 1.9 are deprecated.
<ide> func postBuild(srv *Server, version float64, w http.ResponseWriter, r *http.Requ
<ide> return nil
<ide> }
<ide>
<del>func postContainersCopy(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersCopy(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postContainersCopy(srv *Server, version float64, w http.ResponseWriter, r *
<ide> copyData.Set("Resource", copyData.Get("Resource")[1:])
<ide> }
<ide>
<del> job := srv.Eng.Job("container_copy", vars["name"], copyData.Get("Resource"))
<add> job := eng.Job("container_copy", vars["name"], copyData.Get("Resource"))
<ide> job.Stdout.Add(w)
<ide> if err := job.Run(); err != nil {
<ide> utils.Errorf("%s", err.Error())
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func optionsHandler(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func optionsHandler(eng *engine.Engine, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.WriteHeader(http.StatusOK)
<ide> return nil
<ide> }
<ide> func writeCorsHeaders(w http.ResponseWriter, r *http.Request) {
<ide> w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
<ide> }
<ide>
<del>func makeHttpHandler(srv *Server, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool) http.HandlerFunc {
<add>func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion string) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<ide> // log the request
<ide> utils.Debugf("Calling %s %s", localMethod, localRoute)
<ide> func makeHttpHandler(srv *Server, logging bool, localMethod string, localRoute s
<ide>
<ide> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<ide> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<del> if len(userAgent) == 2 && userAgent[1] != VERSION {
<del> utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], VERSION)
<add> if len(userAgent) == 2 && userAgent[1] != dockerVersion {
<add> utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
<ide> }
<ide> }
<ide> version, err := strconv.ParseFloat(mux.Vars(r)["version"], 64)
<ide> func makeHttpHandler(srv *Server, logging bool, localMethod string, localRoute s
<ide> return
<ide> }
<ide>
<del> if err := handlerFunc(srv, version, w, r, mux.Vars(r)); err != nil {
<add> if err := handlerFunc(eng, version, w, r, mux.Vars(r)); err != nil {
<ide> utils.Errorf("Error: %s", err)
<ide> httpError(w, err)
<ide> }
<ide> func AttachProfiler(router *mux.Router) {
<ide> router.HandleFunc("/debug/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
<ide> }
<ide>
<del>func createRouter(srv *Server, logging, enableCors bool) (*mux.Router, error) {
<add>func createRouter(eng *engine.Engine, logging, enableCors bool, dockerVersion string) (*mux.Router, error) {
<ide> r := mux.NewRouter()
<ide> if os.Getenv("DEBUG") != "" {
<ide> AttachProfiler(r)
<ide> func createRouter(srv *Server, logging, enableCors bool) (*mux.Router, error) {
<ide> localMethod := method
<ide>
<ide> // build the handler function
<del> f := makeHttpHandler(srv, logging, localMethod, localRoute, localFct, enableCors)
<add> f := makeHttpHandler(eng, logging, localMethod, localRoute, localFct, enableCors, dockerVersion)
<ide>
<ide> // add the new route
<ide> if localRoute == "" {
<ide> func createRouter(srv *Server, logging, enableCors bool) (*mux.Router, error) {
<ide> // ServeRequest processes a single http request to the docker remote api.
<ide> // FIXME: refactor this to be part of Server and not require re-creating a new
<ide> // router each time. This requires first moving ListenAndServe into Server.
<del>func ServeRequest(srv *Server, apiversion float64, w http.ResponseWriter, req *http.Request) error {
<del> router, err := createRouter(srv, false, true)
<add>func ServeRequest(eng *engine.Engine, apiversion float64, w http.ResponseWriter, req *http.Request) error {
<add> router, err := createRouter(eng, false, true, "")
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func ServeFd(addr string, handle http.Handler) error {
<ide>
<ide> // ListenAndServe sets up the required http.Server and gets it listening for
<ide> // each addr passed in and does protocol specific checking.
<del>func ListenAndServe(proto, addr string, srv *Server, logging, enableCors bool) error {
<del> r, err := createRouter(srv, logging, enableCors)
<add>func ListenAndServe(proto, addr string, eng *engine.Engine, logging, enableCors bool, dockerVersion string) error {
<add> r, err := createRouter(eng, logging, enableCors, dockerVersion)
<ide> if err != nil {
<ide> return err
<ide> }
<add><path>api/api_unit_test.go
<del><path>http_test.go
<del>package docker
<add>package api
<ide>
<ide> import (
<ide> "fmt"
<ide> import (
<ide> "testing"
<ide> )
<ide>
<add>func TestJsonContentType(t *testing.T) {
<add> if !MatchesContentType("application/json", "application/json") {
<add> t.Fail()
<add> }
<add>
<add> if !MatchesContentType("application/json; charset=utf-8", "application/json") {
<add> t.Fail()
<add> }
<add>
<add> if MatchesContentType("dockerapplication/json", "application/json") {
<add> t.Fail()
<add> }
<add>}
<add>
<ide> func TestGetBoolParam(t *testing.T) {
<ide> if ret, err := getBoolParam("true"); err != nil || !ret {
<ide> t.Fatalf("true -> true, nil | got %t %s", ret, err)
<ide><path>api_unit_test.go
<del>package docker
<del>
<del>import (
<del> "testing"
<del>)
<del>
<del>func TestJsonContentType(t *testing.T) {
<del> if !matchesContentType("application/json", "application/json") {
<del> t.Fail()
<del> }
<del>
<del> if !matchesContentType("application/json; charset=utf-8", "application/json") {
<del> t.Fail()
<del> }
<del>
<del> if matchesContentType("dockerapplication/json", "application/json") {
<del> t.Fail()
<del> }
<del>}
<ide><path>commands.go
<ide> import (
<ide> "encoding/json"
<ide> "errors"
<ide> "fmt"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/auth"
<ide> "github.com/dotcloud/docker/engine"
<ide> func (cli *DockerCli) CmdHelp(args ...string) error {
<ide> return nil
<ide> }
<ide> }
<del> help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[unix://%s]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", DEFAULTUNIXSOCKET)
<add> help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[unix://%s]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", api.DEFAULTUNIXSOCKET)
<ide> for _, command := range [][]string{
<ide> {"attach", "Attach to a running container"},
<ide> {"build", "Build a container from a Dockerfile"},
<ide> func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo b
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), params)
<ide> if err != nil {
<ide> return nil, -1, err
<ide> }
<ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, h
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), in)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, h
<ide> return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
<ide> }
<ide>
<del> if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
<add> if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
<ide> return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
<ide> }
<ide> if _, err := io.Copy(out, resp.Body); err != nil {
<ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea
<ide> re := regexp.MustCompile("/+")
<ide> path = re.ReplaceAllString(path, "/")
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", api.APIVERSION, path), nil)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>docker/docker.go
<ide> package main
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/engine"
<ide> flag "github.com/dotcloud/docker/pkg/mflag"
<ide> "github.com/dotcloud/docker/sysinit"
<ide> func main() {
<ide>
<ide> if defaultHost == "" || *flDaemon {
<ide> // If we do not have a host, default to unix socket
<del> defaultHost = fmt.Sprintf("unix://%s", docker.DEFAULTUNIXSOCKET)
<add> defaultHost = fmt.Sprintf("unix://%s", api.DEFAULTUNIXSOCKET)
<ide> }
<ide> flHosts.Set(defaultHost)
<ide> }
<ide><path>integration/api_test.go
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<ide> "github.com/dotcloud/docker"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/utils"
<ide> "io"
<ide> import (
<ide> func TestGetVersion(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> var err error
<ide> r := httptest.NewRecorder()
<ide> func TestGetVersion(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> // FIXME getting the version should require an actual running Server
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetVersion(t *testing.T) {
<ide> func TestGetInfo(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> job := eng.Job("images")
<ide> initialImages, err := job.Stdout.AddListTable()
<ide> func TestGetInfo(t *testing.T) {
<ide> }
<ide> r := httptest.NewRecorder()
<ide>
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetEvents(t *testing.T) {
<ide>
<ide> r := httptest.NewRecorder()
<ide> setTimeout(t, "", 500*time.Millisecond, func() {
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetEvents(t *testing.T) {
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> job := eng.Job("images")
<ide> initialImages, err := job.Stdout.AddListTable()
<ide> func TestGetImagesJSON(t *testing.T) {
<ide>
<ide> r := httptest.NewRecorder()
<ide>
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r2, req2); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r2, req2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r2, t)
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r3, req3); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r3, req3); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r3, t)
<ide> func TestGetImagesJSON(t *testing.T) {
<ide> func TestGetImagesHistory(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> r := httptest.NewRecorder()
<ide>
<ide> req, err := http.NewRequest("GET", fmt.Sprintf("/images/%s/history", unitTestImageName), nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetImagesHistory(t *testing.T) {
<ide> func TestGetImagesByName(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> req, err := http.NewRequest("GET", "/images/"+unitTestImageName+"/json", nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetImagesByName(t *testing.T) {
<ide> func TestGetContainersJSON(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> job := eng.Job("containers")
<ide> job.SetenvBool("all", true)
<ide> func TestGetContainersJSON(t *testing.T) {
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetContainersJSON(t *testing.T) {
<ide> func TestGetContainersExport(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> // Create a container and remove a file
<ide> containerID := createTestContainer(eng,
<ide> func TestGetContainersExport(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetContainersExport(t *testing.T) {
<ide> func TestGetContainersChanges(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> // Create a container and remove a file
<ide> containerID := createTestContainer(eng,
<ide> func TestGetContainersChanges(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetContainersChanges(t *testing.T) {
<ide> func TestGetContainersTop(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestGetContainersTop(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetContainersTop(t *testing.T) {
<ide> func TestGetContainersByName(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> // Create a container and remove a file
<ide> containerID := createTestContainer(eng,
<ide> func TestGetContainersByName(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostCommit(t *testing.T) {
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostCommit(t *testing.T) {
<ide> func TestPostContainersCreate(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> configJSON, err := json.Marshal(&docker.Config{
<ide> Image: unitTestImageID,
<ide> func TestPostContainersCreate(t *testing.T) {
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersCreate(t *testing.T) {
<ide> func TestPostContainersKill(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersKill(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersKill(t *testing.T) {
<ide> func TestPostContainersRestart(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersRestart(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersRestart(t *testing.T) {
<ide> func TestPostContainersStart(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(
<ide> eng,
<ide> func TestPostContainersStart(t *testing.T) {
<ide> req.Header.Set("Content-Type", "application/json")
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersStart(t *testing.T) {
<ide> }
<ide>
<ide> r = httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> // Starting an already started container should return an error
<ide> func TestPostContainersStart(t *testing.T) {
<ide> func TestRunErrorBindMountRootSource(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(
<ide> eng,
<ide> func TestRunErrorBindMountRootSource(t *testing.T) {
<ide> req.Header.Set("Content-Type", "application/json")
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> if r.Code != http.StatusInternalServerError {
<ide> func TestRunErrorBindMountRootSource(t *testing.T) {
<ide> func TestPostContainersStop(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersStop(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersStop(t *testing.T) {
<ide> func TestPostContainersWait(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersWait(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestPostContainersWait(t *testing.T) {
<ide> func TestPostContainersAttach(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersAttach(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r.ResponseRecorder, t)
<ide> func TestPostContainersAttach(t *testing.T) {
<ide> func TestPostContainersAttachStderr(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestPostContainersAttachStderr(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r.ResponseRecorder, t)
<ide> func TestPostContainersAttachStderr(t *testing.T) {
<ide> func TestDeleteContainers(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> containerID := createTestContainer(eng,
<ide> &docker.Config{
<ide> func TestDeleteContainers(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestDeleteContainers(t *testing.T) {
<ide> func TestOptionsRoute(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<add>
<ide> r := httptest.NewRecorder()
<ide> req, err := http.NewRequest("OPTIONS", "/", nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestOptionsRoute(t *testing.T) {
<ide> func TestGetEnabledCors(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<add>
<ide> r := httptest.NewRecorder()
<ide>
<ide> req, err := http.NewRequest("GET", "/version", nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide> func TestGetEnabledCors(t *testing.T) {
<ide> func TestDeleteImages(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> initialImages := getImages(eng, t, true, "")
<ide>
<ide> func TestDeleteImages(t *testing.T) {
<ide> }
<ide>
<ide> r := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> if r.Code != http.StatusConflict {
<ide> func TestDeleteImages(t *testing.T) {
<ide> }
<ide>
<ide> r2 := httptest.NewRecorder()
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r2, req2); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r2, req2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r2, t)
<ide> func TestDeleteImages(t *testing.T) {
<ide> func TestPostContainersCopy(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer mkRuntimeFromEngine(eng, t).Nuke()
<del> srv := mkServerFromEngine(eng, t)
<ide>
<ide> // Create a container and remove a file
<ide> containerID := createTestContainer(eng,
<ide> func TestPostContainersCopy(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> req.Header.Add("Content-Type", "application/json")
<del> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil {
<add> if err := api.ServeRequest(eng, api.APIVERSION, r, req); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> assertHttpNotError(r, t)
<ide><path>opts.go
<ide> package docker
<ide>
<ide> import (
<ide> "fmt"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/utils"
<ide> "os"
<ide> "path/filepath"
<ide> func ValidateEnv(val string) (string, error) {
<ide> }
<ide>
<ide> func ValidateHost(val string) (string, error) {
<del> host, err := utils.ParseHost(DEFAULTHTTPHOST, DEFAULTHTTPPORT, DEFAULTUNIXSOCKET, val)
<add> host, err := utils.ParseHost(api.DEFAULTHTTPHOST, api.DEFAULTHTTPPORT, api.DEFAULTUNIXSOCKET, val)
<ide> if err != nil {
<ide> return val, err
<ide> }
<ide><path>server.go
<ide> import (
<ide> "encoding/json"
<ide> "errors"
<ide> "fmt"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/auth"
<ide> "github.com/dotcloud/docker/engine"
<ide> func (srv *Server) ListenAndServe(job *engine.Job) engine.Status {
<ide> protoAddrParts := strings.SplitN(protoAddr, "://", 2)
<ide> go func() {
<ide> log.Printf("Listening for HTTP on %s (%s)\n", protoAddrParts[0], protoAddrParts[1])
<del> chErrors <- ListenAndServe(protoAddrParts[0], protoAddrParts[1], srv, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"))
<add> chErrors <- api.ListenAndServe(protoAddrParts[0], protoAddrParts[1], srv.Eng, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"), VERSION)
<ide> }()
<ide> }
<ide> | 8 |
Javascript | Javascript | use assignlanguagemode in texteditor spec | 20b0fc688d73a0120bc293edfd8d5a9fb367aea4 | <ide><path>spec/text-editor-spec.js
<ide> describe('TextEditor', () => {
<ide> })
<ide>
<ide> it('will limit paragraph range to comments', () => {
<del> editor.setGrammar(atom.grammars.grammarForScopeName('source.js'))
<add> atom.grammars.assignLanguageMode(editor.getBuffer(), 'javascript')
<ide> editor.setText(dedent`
<ide> var quicksort = function () {
<ide> /* Single line comment block */
<ide> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
<ide> describe('when a newline is appended with a trailing closing tag behind the cursor (e.g. by pressing enter in the middel of a line)', () => {
<ide> it('indents the new line to the correct level when editor.autoIndent is true and using a curly-bracket language', () => {
<ide> editor.update({autoIndent: true})
<del> editor.setGrammar(atom.grammars.selectGrammar('file.js'))
<add> atom.grammars.assignLanguageMode(editor, 'javascript')
<ide> editor.setText('var test = () => {\n return true;};')
<ide> editor.setCursorBufferPosition([1, 14])
<ide> editor.insertNewline()
<ide> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
<ide> })
<ide>
<ide> it('indents the new line to the current level when editor.autoIndent is true and no increaseIndentPattern is specified', () => {
<del> editor.setGrammar(atom.grammars.selectGrammar('file'))
<add> atom.grammars.assignLanguageMode(editor, 'null grammar')
<ide> editor.update({autoIndent: true})
<ide> editor.setText(' if true')
<ide> editor.setCursorBufferPosition([0, 8])
<ide> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
<ide> it('indents the new line to the correct level when editor.autoIndent is true and using an off-side rule language', async () => {
<ide> await atom.packages.activatePackage('language-coffee-script')
<ide> editor.update({autoIndent: true})
<del> editor.setGrammar(atom.grammars.selectGrammar('file.coffee'))
<add> atom.grammars.assignLanguageMode(editor, 'coffeescript')
<ide> editor.setText('if true\n return trueelse\n return false')
<ide> editor.setCursorBufferPosition([1, 13])
<ide> editor.insertNewline()
<ide> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
<ide> it('indents the new line to the correct level when editor.autoIndent is true', async () => {
<ide> await atom.packages.activatePackage('language-go')
<ide> editor.update({autoIndent: true})
<del> editor.setGrammar(atom.grammars.selectGrammar('file.go'))
<add> atom.grammars.assignLanguageMode(editor, 'go')
<ide> editor.setText('fmt.Printf("some%s",\n "thing")')
<ide> editor.setCursorBufferPosition([1, 10])
<ide> editor.insertNewline()
<ide> describe('TextEditor', () => {
<ide> })
<ide>
<ide> it('does nothing for empty lines and null grammar', () => {
<del> editor.setGrammar(atom.grammars.grammarForScopeName('text.plain.null-grammar'))
<add> atom.grammars.assignLanguageMode(editor, 'null grammar')
<ide> editor.setCursorBufferPosition([10, 0])
<ide> editor.toggleLineCommentsInSelection()
<ide> expect(editor.lineTextForBufferRow(10)).toBe('') | 1 |
Ruby | Ruby | replace shell `which` with native code | d6299af86c6f8304f629184298114ef244e52bd8 | <ide><path>Library/Homebrew/utils.rb
<ide> def puts_columns items, star_items=[]
<ide> end
<ide>
<ide> def which cmd
<del> path = `/usr/bin/which #{cmd} 2>/dev/null`.chomp
<del> if path.empty?
<del> nil
<del> else
<del> Pathname.new(path)
<del> end
<add> dir = ENV['PATH'].split(':').find {|p| File.executable? File.join(p, cmd)}
<add> Pathname.new(File.join(dir, cmd)) unless dir.nil?
<ide> end
<ide>
<ide> def which_editor | 1 |
Mixed | PHP | change cache flush return type | 4543caa9a45adbc2e127e8c92a70158bd191d83b | <ide><path>CHANGELOG-5.4.md
<ide> - Support wildcards in `MessageBag::first()` ([#15217](https://github.com/laravel/framework/pull/15217))
<ide>
<ide> ### Changed
<add>- Cache flush method returns bool ([#15578](https://github.com/laravel/framework/issues/15578))
<ide>
<ide> ### Fixed
<ide>
<ide><path>src/Illuminate/Cache/ApcStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<del> $this->apc->flush();
<add> return $this->apc->flush();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/ApcWrapper.php
<ide> public function delete($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<del> $this->apcu ? apcu_clear_cache() : apc_clear_cache('user');
<add> return $this->apcu ? apcu_clear_cache() : apc_clear_cache('user');
<ide> }
<ide> }
<ide><path>src/Illuminate/Cache/ArrayStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<ide> $this->storage = [];
<add> return true;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/DatabaseStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<del> $this->table()->delete();
<add> return (bool) $this->table()->delete();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/FileStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<ide> if ($this->files->isDirectory($this->directory)) {
<ide> foreach ($this->files->directories($this->directory) as $directory) {
<del> $this->files->deleteDirectory($directory);
<add> if(!$this->files->deleteDirectory($directory)){
<add> return false;
<add> }
<ide> }
<add> return true;
<ide> }
<add> return false;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/MemcachedStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<del> $this->memcached->flush();
<add> return $this->memcached->flush();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Cache/NullStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<ide><path>src/Illuminate/Cache/RedisStore.php
<ide> public function forget($key)
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush()
<ide> {
<del> $this->connection()->flushdb();
<add> return (bool) $this->connection()->flushdb();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Contracts/Cache/Store.php
<ide> public function forget($key);
<ide> /**
<ide> * Remove all items from the cache.
<ide> *
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function flush();
<ide>
<ide><path>tests/Cache/CacheApcStoreTest.php
<ide> public function testForgetMethodProperlyCallsAPC()
<ide> $store = new Illuminate\Cache\ApcStore($apc);
<ide> $store->forget('foo');
<ide> }
<add>
<add> public function testFlushesCached()
<add> {
<add> $apc = $this->getMockBuilder('Illuminate\Cache\ApcWrapper')->setMethods(['flush'])->getMock();
<add> $apc->expects($this->once())->method('flush')->willReturn(true);
<add> $store = new Illuminate\Cache\ApcStore($apc);
<add> $result = $store->flush();
<add> $this->assertTrue($result);
<add> }
<ide> }
<ide><path>tests/Cache/CacheArrayStoreTest.php
<ide> public function testItemsCanBeFlushed()
<ide> $store = new ArrayStore;
<ide> $store->put('foo', 'bar', 10);
<ide> $store->put('baz', 'boom', 10);
<del> $store->flush();
<add> $result = $store->flush();
<add> $this->assertTrue($result);
<ide> $this->assertNull($store->get('foo'));
<ide> $this->assertNull($store->get('baz'));
<ide> }
<ide><path>tests/Cache/CacheDatabaseStoreTest.php
<ide> public function testItemsMayBeFlushedFromCache()
<ide> $store = $this->getStore();
<ide> $table = m::mock('StdClass');
<ide> $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
<del> $table->shouldReceive('delete')->once();
<add> $table->shouldReceive('delete')->once()->andReturn(2);
<ide>
<del> $store->flush();
<add> $result = $store->flush();
<add> $this->assertTrue($result);
<ide> }
<ide>
<ide> public function testIncrementReturnsCorrectValues()
<ide><path>tests/Cache/CacheFileStoreTest.php
<ide> public function testFlushCleansDirectory()
<ide> $files = $this->mockFilesystem();
<ide> $files->expects($this->once())->method('isDirectory')->with($this->equalTo(__DIR__))->will($this->returnValue(true));
<ide> $files->expects($this->once())->method('directories')->with($this->equalTo(__DIR__))->will($this->returnValue(['foo']));
<del> $files->expects($this->once())->method('deleteDirectory')->with($this->equalTo('foo'));
<add> $files->expects($this->once())->method('deleteDirectory')->with($this->equalTo('foo'))->will($this->returnValue(true));
<ide>
<ide> $store = new FileStore($files, __DIR__);
<del> $store->flush();
<add> $result = $store->flush();
<add> $this->assertTrue($result, 'Flush failed');
<add> }
<add>
<add> public function testFlushFailsDirectoryClean()
<add> {
<add> $files = $this->mockFilesystem();
<add> $files->expects($this->once())->method('isDirectory')->with($this->equalTo(__DIR__))->will($this->returnValue(true));
<add> $files->expects($this->once())->method('directories')->with($this->equalTo(__DIR__))->will($this->returnValue(['foo']));
<add> $files->expects($this->once())->method('deleteDirectory')->with($this->equalTo('foo'))->will($this->returnValue(false));
<add>
<add> $store = new FileStore($files, __DIR__);
<add> $result = $store->flush();
<add> $this->assertFalse($result, 'Flush should not have cleared directories');
<ide> }
<ide>
<ide> public function testFlushIgnoreNonExistingDirectory()
<ide> public function testFlushIgnoreNonExistingDirectory()
<ide> $files->expects($this->once())->method('isDirectory')->with($this->equalTo(__DIR__.'--wrong'))->will($this->returnValue(false));
<ide>
<ide> $store = new FileStore($files, __DIR__.'--wrong');
<del> $store->flush();
<add> $result = $store->flush();
<add> $this->assertFalse($result, 'Flush should not clean directory');
<ide> }
<ide>
<ide> protected function mockFilesystem()
<ide><path>tests/Cache/CacheMemcachedStoreTest.php
<ide> public function testForgetMethodProperlyCallsMemcache()
<ide> $store->forget('foo');
<ide> }
<ide>
<add> public function testFlushesCached()
<add> {
<add> if (! class_exists('Memcached')) {
<add> $this->markTestSkipped('Memcached module not installed');
<add> }
<add>
<add> $memcache = $this->getMockBuilder('Memcached')->setMethods(['flush'])->getMock();
<add> $memcache->expects($this->once())->method('flush')->willReturn(true);
<add> $store = new Illuminate\Cache\MemcachedStore($memcache);
<add> $result = $store->flush();
<add> $this->assertTrue($result);
<add> }
<add>
<ide> public function testGetAndSetPrefix()
<ide> {
<ide> if (! class_exists('Memcached')) {
<ide><path>tests/Cache/CacheRedisStoreTest.php
<ide> public function testForgetMethodProperlyCallsRedis()
<ide> $redis->forget('foo');
<ide> }
<ide>
<add> public function testFlushesCached()
<add> {
<add> $redis = $this->getRedis();
<add> $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
<add> $redis->getRedis()->shouldReceive('flushdb')->once()->andReturn('ok');
<add> $result = $redis->flush();
<add> $this->assertTrue($result);
<add> }
<add>
<ide> public function testGetAndSetPrefix()
<ide> {
<ide> $redis = $this->getRedis(); | 16 |
Go | Go | remove todo windows | 208ad80605e5c8c48f77f1b89b25951767135224 | <ide><path>daemon/container_unix.go
<ide> type Container struct {
<ide> AppArmorProfile string
<ide> HostnamePath string
<ide> HostsPath string
<del> ShmPath string // TODO Windows - Factor this out (GH15862)
<del> MqueuePath string // TODO Windows - Factor this out (GH15862)
<add> ShmPath string
<add> MqueuePath string
<ide> ResolvConfPath string
<ide>
<ide> Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility | 1 |
Ruby | Ruby | ask the request for the cookie jar | 1989b20c163e2e344556b4f64e566afb96e93d50 | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def cookie_jar
<ide> end
<ide>
<ide> # :stopdoc:
<add> def have_cookie_jar?
<add> env.key? 'action_dispatch.cookies'.freeze
<add> end
<add>
<ide> def cookie_jar=(jar)
<ide> env['action_dispatch.cookies'.freeze] = jar
<ide> end
<ide> def initialize(app)
<ide> end
<ide>
<ide> def call(env)
<add> request = ActionDispatch::Request.new env
<add>
<ide> status, headers, body = @app.call(env)
<ide>
<del> if cookie_jar = env['action_dispatch.cookies']
<add> if request.have_cookie_jar?
<add> cookie_jar = request.cookie_jar
<ide> unless cookie_jar.committed?
<ide> cookie_jar.write(headers)
<ide> if headers[HTTP_HEADER].respond_to?(:join) | 1 |
Text | Text | update instructions for use with react-redux | 6de763d1e03d9fd8e1792efadb0682f9e3f363bb | <ide><path>docs/usage/UsageWithTypescript.md
<ide> While [React Redux](https://react-redux.js.org) is a separate library from Redux
<ide>
<ide> For a complete guide on how to correctly use React Redux with TypeScript, see **[the "Static Typing" page in the React Redux docs](https://react-redux.js.org/using-react-redux/static-typing)**. This section will highlight the standard patterns.
<ide>
<del>As mentioned above, React Redux doesn't ship with its own type definitions. If you are using TypeScript you should install the [`@types/react-redux` type definitions](https://npm.im/@types/react-redux) from npm.
<add>If you are using TypeScript, the React Redux types are maintained separately in DefinitelyTyped, but included as a dependency of the react-redux package, so they should be installed automatically. If you still need to install them manually, run:
<add>
<add>```sh
<add>npm install @types/react-redux
<add>```
<ide>
<ide> ### Typing the `useSelector` hook
<ide> | 1 |
Javascript | Javascript | replace _questioncancel with a symbol | fec093b6b73b06b83b08e01641ef30e229412283 | <ide><path>lib/readline.js
<ide> const kMincrlfDelay = 100;
<ide> const lineEnding = /\r?\n|\r(?!\n)/;
<ide>
<ide> const kLineObjectStream = Symbol('line object stream');
<add>const kQuestionCancel = Symbol('kQuestionCancel');
<ide>
<ide> const KEYPRESS_DECODER = Symbol('keypress-decoder');
<ide> const ESCAPE_DECODER = Symbol('escape-decoder');
<ide> function Interface(input, output, completer, terminal) {
<ide> };
<ide> }
<ide>
<del> this._questionCancel = FunctionPrototypeBind(_questionCancel, this);
<add> this[kQuestionCancel] = FunctionPrototypeBind(_questionCancel, this);
<ide>
<ide> this.setPrompt(prompt);
<ide>
<ide> Interface.prototype.question = function(query, options, cb) {
<ide>
<ide> if (options.signal) {
<ide> options.signal.addEventListener('abort', () => {
<del> this._questionCancel();
<add> this[kQuestionCancel]();
<ide> }, { once: true });
<ide> }
<ide> | 1 |
Javascript | Javascript | adjust data tests to ensure proper camelcasing | 775caebd617e91e697b3e41ae33d6877e63785aa | <ide><path>src/deprecated.js
<ide> define( [
<ide> "./core",
<ide> "./core/nodeName",
<add> "./core/camelCase",
<ide> "./var/isWindow"
<del>], function( jQuery, nodeName, isWindow ) {
<add>], function( jQuery, nodeName, camelCase, isWindow ) {
<ide>
<ide> "use strict";
<ide>
<ide> jQuery.isArray = Array.isArray;
<ide> jQuery.parseJSON = JSON.parse;
<ide> jQuery.nodeName = nodeName;
<ide> jQuery.isWindow = isWindow;
<add>jQuery.camelCase = camelCase;
<ide>
<ide> } );
<ide><path>test/unit/data.js
<ide> QUnit.test( ".data should not miss attr() set data-* with hyphenated property na
<ide> } );
<ide>
<ide> QUnit.test( ".data always sets data with the camelCased key (gh-2257)", function( assert ) {
<del> assert.expect( 9 );
<add> assert.expect( 18 );
<ide>
<ide> var div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ),
<ide> datas = {
<del> "non-empty": "a string",
<del> "empty-string": "",
<del> "one-value": 1,
<del> "zero-value": 0,
<del> "an-array": [],
<del> "an-object": {},
<del> "bool-true": true,
<del> "bool-false": false,
<add> "non-empty": {
<add> key: "nonEmpty",
<add> value: "a string"
<add> },
<add> "empty-string": {
<add> key: "emptyString",
<add> value: ""
<add> },
<add> "one-value": {
<add> key: "oneValue",
<add> value: 1
<add> },
<add> "zero-value": {
<add> key: "zeroValue",
<add> value: 0
<add> },
<add> "an-array": {
<add> key: "anArray",
<add> value: []
<add> },
<add> "an-object": {
<add> key: "anObject",
<add> value: {}
<add> },
<add> "bool-true": {
<add> key: "boolTrue",
<add> value: true
<add> },
<add> "bool-false": {
<add> key: "boolFalse",
<add> value: false
<add> },
<ide>
<ide> // JSHint enforces double quotes,
<ide> // but JSON strings need double quotes to parse
<ide> // so we need escaped double quotes here
<del> "some-json": "{ \"foo\": \"bar\" }"
<add> "some-json": {
<add> key: "someJson",
<add> value: "{ \"foo\": \"bar\" }"
<add> }
<ide> };
<ide>
<ide> jQuery.each( datas, function( key, val ) {
<del> div.data( key, val );
<add> div.data( key, val.value );
<ide> var allData = div.data();
<ide> assert.equal( allData[ key ], undefined, ".data does not store with hyphenated keys" );
<add> assert.equal( allData[ val.key ], val.value, ".data stores the camelCased key" );
<ide> } );
<ide> } );
<ide>
<ide> QUnit.test( ".data should not strip more than one hyphen when camelCasing (gh-20
<ide> assert.equal( allData[ "nested--Triple" ], "triple", "Key with triple hyphens is correctly camelCased" );
<ide> } );
<ide>
<del>QUnit.test( ".data supports interoperable hyphenated get/set of properties with arbitrary non-null|NaN|undefined values", function( assert ) {
<add>QUnit.test( ".data supports interoperable hyphenated/camelCase get/set of properties with arbitrary non-null|NaN|undefined values", function( assert ) {
<ide>
<ide> var div = jQuery( "<div/>", { id: "hyphened" } ).appendTo( "#qunit-fixture" ),
<ide> datas = {
<del> "non-empty": "a string",
<del> "empty-string": "",
<del> "one-value": 1,
<del> "zero-value": 0,
<del> "an-array": [],
<del> "an-object": {},
<del> "bool-true": true,
<del> "bool-false": false,
<add> "non-empty": {
<add> key: "nonEmpty",
<add> value: "a string"
<add> },
<add> "empty-string": {
<add> key: "emptyString",
<add> value: ""
<add> },
<add> "one-value": {
<add> key: "oneValue",
<add> value: 1
<add> },
<add> "zero-value": {
<add> key: "zeroValue",
<add> value: 0
<add> },
<add> "an-array": {
<add> key: "anArray",
<add> value: []
<add> },
<add> "an-object": {
<add> key: "anObject",
<add> value: {}
<add> },
<add> "bool-true": {
<add> key: "boolTrue",
<add> value: true
<add> },
<add> "bool-false": {
<add> key: "boolFalse",
<add> value: false
<add> },
<ide>
<ide> // JSHint enforces double quotes,
<ide> // but JSON strings need double quotes to parse
<ide> // so we need escaped double quotes here
<del> "some-json": "{ \"foo\": \"bar\" }",
<del> "num-1-middle": true,
<del> "num-end-2": true,
<del> "2-num-start": true
<add> "some-json": {
<add> key: "someJson",
<add> value: "{ \"foo\": \"bar\" }"
<add> },
<add>
<add> "num-1-middle": {
<add> key: "num-1Middle",
<add> value: true
<add> },
<add> "num-end-2": {
<add> key: "numEnd-2",
<add> value: true
<add> },
<add> "2-num-start": {
<add> key: "2NumStart",
<add> value: true
<add> }
<ide> };
<ide>
<del> assert.expect( 12 );
<add> assert.expect( 24 );
<ide>
<ide> jQuery.each( datas, function( key, val ) {
<del> div.data( key, val );
<add> div.data( key, val.value );
<ide>
<del> assert.deepEqual( div.data( key ), val, "get: " + key );
<add> assert.deepEqual( div.data( key ), val.value, "get: " + key );
<add> assert.deepEqual( div.data( val.key ), val.value, "get: " + val.key );
<ide> } );
<ide> } );
<ide>
<del>QUnit.test( ".data supports interoperable removal of hyphenated properties", function( assert ) {
<add>QUnit.test( ".data supports interoperable removal of hyphenated/camelCase properties", function( assert ) {
<ide> var div = jQuery( "<div/>", { id: "hyphened" } ).appendTo( "#qunit-fixture" ),
<ide> datas = {
<ide> "non-empty": "a string",
<ide> QUnit.test( ".data supports interoperable removal of hyphenated properties", fun
<ide> "some-json": "{ \"foo\": \"bar\" }"
<ide> };
<ide>
<del> assert.expect( 18 );
<add> assert.expect( 27 );
<ide>
<ide> jQuery.each( datas, function( key, val ) {
<ide> div.data( key, val );
<ide>
<ide> assert.deepEqual( div.data( key ), val, "get: " + key );
<add> assert.deepEqual( div.data( jQuery.camelCase( key ) ), val, "get: " + jQuery.camelCase( key ) );
<ide>
<ide> div.removeData( key );
<ide> | 2 |
Text | Text | improve instructions for verifying binaries | 004f8b037e8e89987dbbe6314ba0ddf45d6719b4 | <ide><path>README.md
<ide> directory under _docs_ or at <https://nodejs.org/download/docs/>.
<ide>
<ide> ### Verifying Binaries
<ide>
<del>Current, LTS, and Nightly download directories all contain a SHASUMS256.txt
<del>file that lists the SHA checksums for each file available for
<del>download.
<add>Download directories contain a SHASUMS256.txt file with SHA checksums for the
<add>files.
<ide>
<del>The SHASUMS256.txt can be downloaded using `curl`.
<add>To download SHASUMS256.txt using `curl`:
<ide>
<ide> ```console
<ide> $ curl -O https://nodejs.org/dist/vx.y.z/SHASUMS256.txt
<ide> it through `sha256sum` with a command such as:
<ide> $ grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c -
<ide> ```
<ide>
<del>Current and LTS releases (but not Nightlies) also have the GPG detached
<del>signature of SHASUMS256.txt available as SHASUMS256.txt.sig. You can use `gpg`
<del>to verify that SHASUMS256.txt has not been tampered with.
<del>
<del>To verify SHASUMS256.txt has not been altered, you will first need to import
<del>all of the GPG keys of individuals authorized to create releases. They are
<del>listed at the bottom of this README under [Release Team](#release-team).
<del>Use a command such as this to import the keys:
<add>For Current and LTS, the GPG detached signature of SHASUMS256.txt is in
<add>SHASUMS256.txt.sig. You can use it with `gpg` to verify the integrity of
<add>SHASUM256.txt. You will first need to import all the GPG keys of individuals
<add>authorized to create releases. They are at the bottom of this README under
<add>[Release Team](#release-team). To import the keys:
<ide>
<ide> ```console
<ide> $ gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
<ide> Next, download the SHASUMS256.txt.sig for the release:
<ide> $ curl -O https://nodejs.org/dist/vx.y.z/SHASUMS256.txt.sig
<ide> ```
<ide>
<del>After downloading the appropriate SHASUMS256.txt and SHASUMS256.txt.sig files,
<del>you can then use `gpg --verify SHASUMS256.txt.sig SHASUMS256.txt` to verify
<del>that the file has been signed by an authorized member of the Node.js team.
<del>
<del>Once verified, use the SHASUMS256.txt file to get the checksum for
<del>the binary verification command above.
<add>Then use `gpg --verify SHASUMS256.txt.sig SHASUMS256.txt` to verify
<add>the file's signature.
<ide>
<ide> ## Building Node.js
<ide> | 1 |
Text | Text | remove broken link from licence | 45c05c709718c28a6c4c6e294c538b9874e0ef03 | <ide><path>README.md
<ide> To help you get your feet wet and get you familiar with our contribution process
<ide> ### License
<ide>
<ide> React is [MIT licensed](./LICENSE).
<del>
<del>React documentation is [Creative Commons licensed](./LICENSE-docs). | 1 |
Ruby | Ruby | fix assertion in `test_delete_multi` | 9020c78dde1942b5caecf2f1870fe746a8b08bbb | <ide><path>activesupport/test/cache/behaviors/cache_store_behavior.rb
<ide> def test_delete_multi
<ide> @cache.write("foo", "bar")
<ide> assert @cache.exist?("foo")
<ide> @cache.write("hello", "world")
<del> assert @cache.exist?("foo")
<add> assert @cache.exist?("hello")
<ide> assert_equal 2, @cache.delete_multi(["foo", "does_not_exist", "hello"])
<ide> assert_not @cache.exist?("foo")
<ide> assert_not @cache.exist?("hello") | 1 |
Text | Text | remove personal pronoun usage in policy.md | 73f2dbc911e16a3b50fc9a1236d9bed7d9e04d7a | <ide><path>doc/api/policy.md
<ide> only with care after auditing a module to ensure its behavior is valid.
<ide>
<ide> #### Example: Patched Dependency
<ide>
<del>Since a dependency can be redirected, you can provide attenuated or modified
<del>forms of dependencies as fits your application. For example, you could log
<del>data about timing of function durations by wrapping the original:
<add>Redirected dependencies can provide attenuated or modified functionality as fits
<add>the application. For example, log data about timing of function durations by
<add>wrapping the original:
<ide>
<ide> ```js
<ide> const original = require('fn'); | 1 |
Javascript | Javascript | fix debug for dnsopts | 7f63449fde070455b337cd4b8e094d5366eb2dd8 | <ide><path>lib/net.js
<ide> function lookupAndConnect(self, options) {
<ide> dnsopts.hints = dns.ADDRCONFIG | dns.V4MAPPED;
<ide>
<ide> debug('connect: find host ' + host);
<del> debug('connect: dns options ' + dnsopts);
<add> debug('connect: dns options', dnsopts);
<ide> self._host = host;
<ide> var lookup = options.lookup || dns.lookup;
<ide> lookup(host, dnsopts, function(err, ip, addressType) { | 1 |
Ruby | Ruby | avoid duplication using _find_all | 0b26cc41dbd8c57eb382318a63c4272de3d2e4e9 | <ide><path>actionview/lib/action_view/template/resolver.rb
<ide> def find_all(name, prefix = nil, partial = false, details = {}, key = nil, local
<ide> locals = locals.map(&:to_s).sort!.freeze
<ide>
<ide> cached(key, [name, prefix, partial], details, locals) do
<del> find_templates(name, prefix, partial, details, locals)
<add> _find_all(name, prefix, partial, details, key, locals)
<ide> end
<ide> end
<ide>
<ide> def find_all_with_query(query) # :nodoc:
<ide>
<ide> private
<ide>
<add> def _find_all(name, prefix, partial, details, key, locals)
<add> find_templates(name, prefix, partial, details, locals)
<add> end
<add>
<ide> delegate :caching?, to: :class
<ide>
<ide> # This is what child classes implement. No defaults are needed
<ide> def clear_cache
<ide> super()
<ide> end
<ide>
<del> def find_all(name, prefix = nil, partial = false, details = {}, key = nil, locals = [])
<del> locals = locals.map(&:to_s).sort!.freeze
<del>
<del> cached(key, [name, prefix, partial], details, locals) do
<del> find_templates(name, prefix, partial, details, locals, cache: !!key)
<del> end
<del> end
<del>
<ide> private
<ide>
<del> def find_templates(name, prefix, partial, details, locals, cache: true)
<add> def _find_all(name, prefix, partial, details, key, locals)
<ide> path = Path.build(name, prefix, partial)
<del> query(path, details, details[:formats], locals, cache: cache)
<add> query(path, details, details[:formats], locals, cache: !!key)
<ide> end
<ide>
<ide> def query(path, details, formats, locals, cache:) | 1 |
Ruby | Ruby | fix greedy outdated command | ac2f52cef33bd374c945e51e9242859f0849bd73 | <ide><path>Library/Homebrew/cask/cask.rb
<ide> def outdated_versions(greedy: false, greedy_latest: false, greedy_auto_updates:
<ide> version
<ide> end
<ide>
<del> if greedy || greedy_latest || (greedy_auto_updates && auto_updates)
<del> if latest_version.latest?
<del> return versions if outdated_download_sha?
<add> if latest_version.latest?
<add> return versions if (greedy || greedy_latest) && outdated_download_sha?
<ide>
<del> return []
<del> end
<del> elsif auto_updates
<add> return []
<add> elsif auto_updates && !(greedy || greedy_auto_updates)
<ide> return []
<ide> end
<ide> | 1 |
PHP | PHP | fix cs error | 321f0c9c2726535591d78713083a8b57365d0f2e | <ide><path>tests/TestCase/Http/MiddlewareQueueTest.php
<ide> namespace Cake\Test\TestCase\Http;
<ide>
<ide> use Cake\Core\Configure;
<del>use Cake\Http\Middleware\CallableMiddleware;
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\TestSuite\TestCase;
<ide> use TestApp\Middleware\DumbMiddleware; | 1 |
Javascript | Javascript | add await to the async isvalidgitdirectory | 15b859a2bede85a0eb58bbe007fa048c5106ca92 | <ide><path>src/git-repository-provider.js
<ide> async function findGitDirectory(directory) {
<ide> if (
<ide> typeof gitDir.exists === 'function' &&
<ide> (await gitDir.exists()) &&
<del> isValidGitDirectory(gitDir)
<add> (await isValidGitDirectory(gitDir))
<ide> ) {
<ide> return gitDir;
<ide> } else if (directory.isRoot()) { | 1 |
Python | Python | add fmod and modf as mandatory functions | 6da52cd0fe2b2110cd6d7274d29a9bbb58f44551 | <ide><path>numpy/core/setup.py
<ide> def name_to_defsymb(name):
<ide> # Mandatory functions: if not found, fail the build
<ide> mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs",
<ide> "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos",
<del> "atan"]
<add> "atan", "fmod", "modf"]
<ide>
<ide> # Standard functions which may not be available and for which we have a
<ide> # replacement implementation | 1 |
Text | Text | add a link to braumeister.org to the readme | a671a13b24d1895ae80c90e040b6647192a9dfe8 | <ide><path>README.md
<ide> What Packages Are Available?
<ide> 1. You can [browse the Formula folder on GitHub][formula].
<ide> 2. Or type `brew search` for a list.
<ide> 3. Or run `brew server` to browse packages off of a local web server.
<add>4. Or visit [braumeister.org][braumeister] to browse packages online.
<ide>
<ide> More Documentation
<ide> ------------------
<ide> I'm [Max Howell][mxcl] and I'm a splendid chap.
<ide> [wiki]:http://wiki.github.com/mxcl/homebrew
<ide> [mxcl]:http://twitter.com/mxcl
<ide> [formula]:http://github.com/mxcl/homebrew/tree/master/Library/Formula/
<add>[braumeister]:http://braumeister.org | 1 |
Text | Text | remove all immutable data libs except immer | 03c835da2dc800843526141442cc45b0edeb9a36 | <ide><path>docs/introduction/Ecosystem.md
<ide> store.dispatch({
<ide>
<ide> ## Immutable Data
<ide>
<del>#### Data Structures
<del>
<del>**[rtfeldman/seamless-immutable](https://github.com/rtfeldman/seamless-immutable)** <br />
<del>Frozen immutable arrays/objects, backwards-compatible with JS
<del>
<del>```js
<del>const array = Immutable(['totally', 'immutable', { a: 42 }])
<del>array[0] = 'edited' // does nothing
<del>```
<del>
<del>**[planttheidea/crio](https://github.com/planttheidea/crio)** <br />
<del>Immutable JS objects with a natural API
<del>
<del>```js
<del>const foo = crio(['foo'])
<del>const fooBar = foo.push('bar') // new array: ['foo', 'bar']
<del>```
<del>
<del>**[aearly/icepick](https://github.com/aearly/icepick)** <br />
<del>Utilities for treating frozen JS objects as persistent immutable collections.
<del>
<del>```js
<del>const newObj = icepick.assocIn({ c: { d: 'bar' } }, ['c', 'd'], 'baz')
<del>const obj3 = icepicke.merge(obj1, obj2)
<del>```
<del>
<del>#### Immutable Update Utilities
<del>
<del>**[mweststrate/immer](https://github.com/mweststrate/immer)** <br />
<add>**[ImmerJS/immer](https://github.com/immerjs/immer)** <br />
<ide> Immutable updates with normal mutative code, using Proxies
<ide>
<ide> ```js
<ide> const nextState = produce(baseState, draftState => {
<ide> })
<ide> ```
<ide>
<del>**[kolodny/immutability-helper](https://github.com/kolodny/immutability-helper)** <br />
<del>A drop-in replacement for react-addons-update
<del>
<del>```js
<del>const newData = update(myData, {
<del> x: { y: { z: { $set: 7 } } },
<del> a: { b: { $push: [9] } }
<del>})
<del>```
<del>
<del>**[debitoor/dot-prop-immutable](https://github.com/debitoor/dot-prop-immutable)** <br />
<del>Immutable version of the dot-prop lib, with some extensions
<del>
<del>```js
<del>const newState = dotProp.set(state, `todos.${index}.complete`, true)
<del>const endOfArray = dotProp.get(obj, 'foo.$end')
<del>```
<del>
<ide> ## Side Effects
<ide>
<ide> #### Widely Used | 1 |
Text | Text | add v3.19.0-beta.2 to changelog | a41da5dd39739f3ef146dd71426c7e2f10f40dc5 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.19.0-beta.2 (April 27, 2020)
<add>
<add>- [#18913](https://github.com/emberjs/ember.js/pull/18913) [BUGFIX] Update to glimmer-vm 0.51.0.
<add>- [#18919](https://github.com/emberjs/ember.js/pull/18919) [BUGFIX] Add error for modifier manager without capabilities.
<add>
<ide> ### v3.19.0-beta.1 (April 14, 2020)
<ide>
<ide> - [#18828](https://github.com/emberjs/ember.js/pull/18828) [BUGFIX] Prepend 'TODO: ' to 'Replace this with your real tests' comments in generated tests | 1 |
PHP | PHP | fix typo in documentation | 7a4f54f917a3445a7d9743a453b5b24ba078c9aa | <ide><path>src/Database/Query.php
<ide> public function limit($num) {
<ide> *
<ide> * {{{
<ide> * $query->offset(10) // generates OFFSET 10
<del> * $query->limit($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
<add> * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
<ide> * }}}
<ide> *
<ide> * @param int|ExpressionInterface $num number of records to be skipped | 1 |
Javascript | Javascript | make this work as an es6 module | 63be4938a7251adb6792a4213696c1dde5457763 | <ide><path>threejs/resources/webgl-debug-helper.js
<ide> * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> */
<ide>
<del>/* global define */
<add>/* global define, globalThis */
<ide>
<ide> (function(root, factory) { // eslint-disable-line
<ide> if (typeof define === 'function' && define.amd) {
<ide> // Browser globals
<ide> root.webglDebugHelper = factory.call(root);
<ide> }
<del>}(this, function() {
<add>}(this || globalThis, function() {
<ide> 'use strict'; // eslint-disable-line
<ide>
<ide> //------------ [ from https://github.com/KhronosGroup/WebGLDeveloperTools ] | 1 |
Javascript | Javascript | fix ident config position | 9c392ae397b31d6b5522d93dc03ebddff1fb1cf5 | <ide><path>test/configCases/loaders/remaining-request/webpack.config.js
<ide> module.exports = {
<ide> "./loader1",
<ide> {
<ide> loader: "./loader2",
<add> ident: "loader2",
<ide> options: {
<del> ident: "loader2",
<ide> f: function() {
<ide> return "ok";
<ide> } | 1 |
Javascript | Javascript | remove unused type | b4d782fb946aea1b464cb0de5c9c3f929a3408a2 | <ide><path>lib/optimize/ConcatenatedModule.js
<ide> const propertyAccess = require("../util/propertyAccess");
<ide> /** @typedef {import("../WebpackError")} WebpackError */
<ide> /** @typedef {import("../util/Hash")} Hash */
<ide>
<del>/**
<del> * @typedef {Object} CachedSourceEntry
<del> * @property {string} hash the hash value
<del> */
<del>
<ide> /**
<ide> * @typedef {Object} ReexportInfo
<ide> * @property {Module} module | 1 |
Python | Python | update error message | 2a0892864c350921bb29d97b48c43d25ed807fe7 | <ide><path>libcloud/common/digitalocean.py
<ide> class DigitalOcean_v1_Error(LibcloudError):
<ide> supported.
<ide> """
<ide>
<del> def __init__(self, value=('Version 1 of the DigitalOcean API reached end'
<del> ' of life on November 9, 2015. Please use the v2 driver.'),
<add> def __init__(self,
<add> value=('Driver no longer supported: Version 1 of the '
<add> 'DigitalOcean API reached end of life on November 9, '
<add> '2015. Use the v2 driver. Please visit: '
<add> 'https://developers.digitalocean.com/documentation/changelog/api-v1/sunsetting-api-v1/'), # noqa: E501
<ide> driver=None):
<ide> super(DigitalOcean_v1_Error, self).__init__(value, driver=driver)
<ide> | 1 |
Python | Python | use list to be safe | 403fa31ec88b95afb5bac67febd1db40006250bb | <ide><path>airflow/jobs.py
<ide> def prioritize_queued(self, session, executor, dagbag):
<ide> else:
<ide> d[ti.pool].append(ti)
<ide>
<del> for pool, tis in d.items():
<add> for pool, tis in list(d.items()):
<ide> open_slots = pools[pool].open_slots(session=session)
<ide> if open_slots > 0:
<ide> tis = sorted( | 1 |
Ruby | Ruby | escape interpolated string in regexp | bfa19b338518f50ec7e5c2d2ed4919fa50217dee | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_text
<ide> end
<ide> bin_names.each do |name|
<ide> ["system", "shell_output", "pipe_output"].each do |cmd|
<del> if text =~ /(def test|test do).*#{cmd}[\(\s]+['"]#{name}[\s'"]/m
<add> if text =~ /(def test|test do).*#{cmd}[\(\s]+['"]#{Regexp.escape name}[\s'"]/m
<ide> problem %(fully scope test #{cmd} calls e.g. #{cmd} "\#{bin}/#{name}")
<ide> end
<ide> end | 1 |
Java | Java | check actual cache value for unwrapped optional | fdb31cd715f4a8811fbbe0b541b54ee5f65fa8df | <ide><path>spring-context/src/test/java/org/springframework/cache/CacheReproTests.java
<ide> public void spr13081ConfigFailIfCacheResolverReturnsNullCacheName() {
<ide> public void spr14230AdaptsToOptional() {
<ide> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Spr14230Config.class);
<ide> Spr14230Service bean = context.getBean(Spr14230Service.class);
<add> Cache cache = context.getBean(CacheManager.class).getCache("itemCache");
<ide>
<ide> TestBean tb = new TestBean("tb1");
<ide> bean.insertItem(tb);
<ide> assertSame(tb, bean.findById("tb1").get());
<add> assertSame(tb, cache.get("tb1").get());
<add>
<add> cache.clear();
<add> TestBean tb2 = bean.findById("tb1").get();
<add> assertNotSame(tb, tb2);
<add> assertSame(tb2, cache.get("tb1").get());
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | handle arrays of images | 65ae4afc8fce25dae226d9a367902339dbd94403 | <ide><path>threejs/resources/editor.js
<ide> function fixSourceLinks(url, source) {
<ide> const srcRE = /(src=)"(.*?)"/g;
<ide> const linkRE = /(href=)"(.*?")/g;
<ide> const imageSrcRE = /((?:image|img)\.src = )"(.*?)"/g;
<del> const loaderLoadRE = /(loader.load[a-z]*\()('|")(.*?)('|")/ig;
<add> const loaderLoadRE = /(loader\.load[a-z]*\()('|")(.*?)('|")/ig;
<add> const loaderArrayLoadRE = /(loader\.load[a-z]*\(\[)([\s\S]*?)(\])/ig;
<add> const arrayLineRE = /^(\s*["|'])([\s\S]*?)(["|']*$)/;
<ide> const urlPropRE = /(url:\s*)('|")(.*?)('|")/g;
<ide> const prefix = getPrefix(url);
<ide>
<ide> function fixSourceLinks(url, source) {
<ide> function makeLinkFDedQuotes(match, fn, q1, url, q2) {
<ide> return fn + q1 + addPrefix(url) + q2;
<ide> }
<add> function makeArrayLinksFDed(match, prefix, arrayStr, suffix) {
<add> const lines = arrayStr.split(',').map((line) => {
<add> const m = arrayLineRE.exec(line);
<add> return m
<add> ? `${m[1]}${addPrefix(m[2])}${m[3]}`
<add> : line;
<add> });
<add> return `${prefix}${lines.join(',')}${suffix}`;
<add> }
<ide>
<ide> source = source.replace(srcRE, makeLinkFQed);
<ide> source = source.replace(linkRE, makeLinkFQed);
<ide> source = source.replace(imageSrcRE, makeLinkFQed);
<ide> source = source.replace(urlPropRE, makeLinkFDedQuotes);
<ide> source = source.replace(loaderLoadRE, makeLinkFDedQuotes);
<add> source = source.replace(loaderArrayLoadRE, makeArrayLinksFDed);
<ide>
<ide> return source;
<ide> } | 1 |
Java | Java | remove code duplication in modelandviewassert | ff8a6e8fdb147e1b988c1ca5b4c8b3008b67534d | <ide><path>spring-test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.test.web;
<ide>
<add>import static org.springframework.test.util.AssertionErrors.*;
<add>
<ide> import java.util.Collections;
<ide> import java.util.Comparator;
<ide> import java.util.HashSet;
<ide> public abstract class ModelAndViewAssert {
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public static <T> T assertAndReturnModelAttributeOfType(ModelAndView mav, String modelName, Class<T> expectedType) {
<del> assertCondition(mav != null, "ModelAndView is null");
<del> assertCondition(mav.getModel() != null, "Model is null");
<add> assertTrue("ModelAndView is null", mav != null);
<add> assertTrue("Model is null", mav.getModel() != null);
<ide> Object obj = mav.getModel().get(modelName);
<del> assertCondition(obj != null, "Model attribute with name '" + modelName + "' is null");
<del> assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '"
<del> + expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'");
<add> assertTrue("Model attribute with name '" + modelName + "' is null", obj != null);
<add> assertTrue("Model attribute is not of expected type '" + expectedType.getName() + "' but rather of type '"
<add> + obj.getClass().getName() + "'", expectedType.isAssignableFrom(obj.getClass()));
<ide> return (T) obj;
<ide> }
<ide>
<ide> public static <T> T assertAndReturnModelAttributeOfType(ModelAndView mav, String
<ide> */
<ide> @SuppressWarnings("rawtypes")
<ide> public static void assertCompareListModelAttribute(ModelAndView mav, String modelName, List expectedList) {
<del> assertCondition(mav != null, "ModelAndView is null");
<add> assertTrue("ModelAndView is null", mav != null);
<ide> List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class);
<del> assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size()
<del> + "' while size of expected list is '" + expectedList.size() + "'");
<del> assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName
<del> + "' is not equal to the expected list.");
<add> assertTrue(
<add> "Size of model list is '" + modelList.size() + "' while size of expected list is '" + expectedList.size()
<add> + "'", expectedList.size() == modelList.size());
<add> assertTrue("List in model under name '" + modelName + "' is not equal to the expected list.",
<add> expectedList.equals(modelList));
<ide> }
<ide>
<ide> /**
<ide> public static void assertCompareListModelAttribute(ModelAndView mav, String mode
<ide> * <code>null</code>)
<ide> */
<ide> public static void assertModelAttributeAvailable(ModelAndView mav, String modelName) {
<del> assertCondition(mav != null, "ModelAndView is null");
<del> assertCondition(mav.getModel() != null, "Model is null");
<del> assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName
<del> + "' is not available");
<add> assertTrue("ModelAndView is null", mav != null);
<add> assertTrue("Model is null", mav.getModel() != null);
<add> assertTrue("Model attribute with name '" + modelName + "' is not available",
<add> mav.getModel().containsKey(modelName));
<ide> }
<ide>
<ide> /**
<ide> public static void assertModelAttributeAvailable(ModelAndView mav, String modelN
<ide> * @param expectedValue the model value
<ide> */
<ide> public static void assertModelAttributeValue(ModelAndView mav, String modelName, Object expectedValue) {
<del> assertCondition(mav != null, "ModelAndView is null");
<add> assertTrue("ModelAndView is null", mav != null);
<ide> Object modelValue = assertAndReturnModelAttributeOfType(mav, modelName, Object.class);
<del> assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName
<del> + "' is not the same as the expected value which was '" + expectedValue + "'");
<add> assertTrue("Model value with name '" + modelName + "' is not the same as the expected value which was '"
<add> + expectedValue + "'", modelValue.equals(expectedValue));
<ide> }
<ide>
<ide> /**
<ide> public static void assertModelAttributeValue(ModelAndView mav, String modelName,
<ide> * @param expectedModel the expected model
<ide> */
<ide> public static void assertModelAttributeValues(ModelAndView mav, Map<String, Object> expectedModel) {
<del> assertCondition(mav != null, "ModelAndView is null");
<del> assertCondition(mav.getModel() != null, "Model is null");
<add> assertTrue("ModelAndView is null", mav != null);
<add> assertTrue("Model is null", mav.getModel() != null);
<ide>
<ide> if (!mav.getModel().keySet().equals(expectedModel.keySet())) {
<ide> StringBuilder sb = new StringBuilder("Keyset of expected model does not match.\n");
<ide> public static void assertModelAttributeValues(ModelAndView mav, Map<String, Obje
<ide> public static void assertSortAndCompareListModelAttribute(ModelAndView mav, String modelName, List expectedList,
<ide> Comparator comparator) {
<ide>
<del> assertCondition(mav != null, "ModelAndView is null");
<add> assertTrue("ModelAndView is null", mav != null);
<ide> List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class);
<ide>
<del> assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size()
<del> + "' while size of expected list is '" + expectedList.size() + "'");
<add> assertTrue(
<add> "Size of model list is '" + modelList.size() + "' while size of expected list is '" + expectedList.size()
<add> + "'", expectedList.size() == modelList.size());
<ide>
<ide> if (comparator != null) {
<ide> Collections.sort(modelList, comparator);
<ide> public static void assertSortAndCompareListModelAttribute(ModelAndView mav, Stri
<ide> Collections.sort(expectedList);
<ide> }
<ide>
<del> assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName
<del> + "' is not equal to the expected list.");
<add> assertTrue("List in model under name '" + modelName + "' is not equal to the expected list.",
<add> expectedList.equals(modelList));
<ide> }
<ide>
<ide> /**
<ide> public static void assertSortAndCompareListModelAttribute(ModelAndView mav, Stri
<ide> * @param expectedName the name of the model value
<ide> */
<ide> public static void assertViewName(ModelAndView mav, String expectedName) {
<del> assertCondition(mav != null, "ModelAndView is null");
<del> assertCondition(ObjectUtils.nullSafeEquals(expectedName, mav.getViewName()), "View name is not equal to '"
<del> + expectedName + "' but was '" + mav.getViewName() + "'");
<del> }
<del>
<del> /**
<del> * Fails by throwing an <code>AssertionError</code> with the supplied
<del> * <code>message</code>.
<del> *
<del> * @param message the exception message to use
<del> * @see #assertCondition(boolean,String)
<del> */
<del> private static void fail(String message) {
<del> throw new AssertionError(message);
<del> }
<del>
<del> /**
<del> * Assert the provided boolean <code>condition</code>, throwing
<del> * <code>AssertionError</code> with the supplied <code>message</code> if the
<del> * test result is <code>false</code>.
<del> *
<del> * @param condition a boolean expression
<del> * @param message the exception message to use if the assertion fails
<del> * @see #fail(String)
<del> */
<del> private static void assertCondition(boolean condition, String message) {
<del> if (!condition) {
<del> fail(message);
<del> }
<add> assertTrue("ModelAndView is null", mav != null);
<add> assertTrue("View name is not equal to '" + expectedName + "' but was '" + mav.getViewName() + "'",
<add> ObjectUtils.nullSafeEquals(expectedName, mav.getViewName()));
<ide> }
<ide>
<ide> private static void appendNonMatchingSetsErrorMessage(Set<String> assertionSet, Set<String> incorrectSet, | 1 |
Python | Python | remove hardcoded fontname in visualize_util | 50d3fddead17b0fb8ffe315a2b3a585d7bcb3055 | <ide><path>keras/utils/visualize_util.py
<ide> def __call__(self, model, recursive=True, show_shape=False,
<ide> self.g = pydot.Dot()
<ide> self.g.set('rankdir', 'TB')
<ide> self.g.set('concentrate', True)
<del> self.g.set_node_defaults(shape='record', fontname="Fira Mono")
<add> self.g.set_node_defaults(shape='record')
<ide>
<ide> if hasattr(model, 'outputs'):
<ide> # Graph | 1 |
Python | Python | add ma for scons build | 16aff17e96d88f474ea41a3570e22bde803d9dec | <ide><path>numpy/ma/setupscons.py
<add>#!/usr/bin/env python
<add>__author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)"
<add>__version__ = '1.0'
<add>__revision__ = "$Revision: 3473 $"
<add>__date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
<add>
<add>import os
<add>
<add>def configuration(parent_package='',top_path=None):
<add> from numpy.distutils.misc_util import Configuration
<add> config = Configuration('ma',parent_package,top_path)
<add> config.add_data_dir('tests')
<add> return config
<add>
<add>if __name__ == "__main__":
<add> from numpy.distutils.core import setup
<add> config = configuration(top_path='').todict()
<add> setup(**config)
<ide><path>numpy/setupscons.py
<ide> def configuration(parent_package='',top_path=None):
<ide> config.add_subpackage('fft')
<ide> config.add_subpackage('linalg')
<ide> config.add_subpackage('random')
<add> config.add_subpackage('ma')
<ide> config.add_data_dir('doc')
<ide> config.add_data_dir('tests')
<ide> config.scons_make_config_py() # installs __config__.py | 2 |
Javascript | Javascript | fix regression in unlistening signals | e9eb2ec1c491e82dda27fe07d0eaf14ff569351b | <ide><path>src/node.js
<ide> // Load events module in order to access prototype elements on process like
<ide> // process.addListener.
<ide> var signalWraps = {};
<del> var addListener = process.addListener;
<del> var removeListener = process.removeListener;
<ide>
<ide> function isSignal(event) {
<ide> return event.slice(0, 3) === 'SIG' &&
<ide> startup.lazyConstants().hasOwnProperty(event);
<ide> }
<ide>
<del> // Wrap addListener for the special signal types
<del> process.on = process.addListener = function(type, listener) {
<add> // Detect presence of a listener for the special signal types
<add> process.on('newListener', function(type, listener) {
<ide> if (isSignal(type) &&
<ide> !signalWraps.hasOwnProperty(type)) {
<ide> var Signal = process.binding('signal_wrap').Signal;
<ide>
<ide> signalWraps[type] = wrap;
<ide> }
<add> });
<ide>
<del> return addListener.apply(this, arguments);
<del> };
<del>
<del> process.removeListener = function(type, listener) {
<del> var ret = removeListener.apply(this, arguments);
<del> if (isSignal(type)) {
<del> assert(signalWraps.hasOwnProperty(type));
<del>
<del> if (NativeModule.require('events').listenerCount(this, type) === 0) {
<del> signalWraps[type].close();
<del> delete signalWraps[type];
<del> }
<add> process.on('removeListener', function(type, listener) {
<add> if (signalWraps.hasOwnProperty(type) &&
<add> NativeModule.require('events').listenerCount(this, type) === 0) {
<add> signalWraps[type].close();
<add> delete signalWraps[type];
<ide> }
<del>
<del> return ret;
<del> };
<add> });
<ide> };
<ide>
<ide>
<ide><path>test/parallel/test-process-remove-all-signal-listeners.js
<add>if (process.platform === 'win32') {
<add> // Win32 doesn't have signals, just a kindof emulation, insufficient
<add> // for this test to apply.
<add> return;
<add>}
<add>
<add>var assert = require('assert');
<add>var spawn = require('child_process').spawn;
<add>var ok;
<add>
<add>if (process.argv[2] !== '--do-test') {
<add> // We are the master, fork a child so we can verify it exits with correct
<add> // status.
<add> process.env.DOTEST = 'y';
<add> var child = spawn(process.execPath, [__filename, '--do-test']);
<add>
<add> child.once('exit', function(code, signal) {
<add> assert.equal(signal, 'SIGINT');
<add> ok = true;
<add> });
<add>
<add> process.on('exit', function() {
<add> assert(ok);
<add> });
<add>
<add> return;
<add>}
<add>
<add>process.on('SIGINT', function() {
<add> // Remove all handlers and kill ourselves. We should terminate by SIGINT
<add> // now that we have no handlers.
<add> process.removeAllListeners('SIGINT');
<add> process.kill(process.pid, 'SIGINT');
<add>});
<add>
<add>// Signal handlers aren't sufficient to keep node alive, so resume stdin
<add>process.stdin.resume();
<add>
<add>// Demonstrate that signals are being handled
<add>process.kill(process.pid, 'SIGINT'); | 2 |
Ruby | Ruby | move formula resources to softwarespec | 6116450328307530d6d25a3fa5b9c34e2a055f1f | <ide><path>Library/Homebrew/formula.rb
<del>require 'resource'
<ide> require 'dependency_collector'
<ide> require 'formula_support'
<ide> require 'formula_lock'
<ide> def initialize name='__UNKNOWN__', path=nil
<ide> end
<ide>
<ide> @pin = FormulaPin.new(self)
<del>
<del> @resources = self.class.resources
<del> @resources.each_value { |r| r.owner = self }
<ide> end
<ide>
<ide> def set_spec(name)
<ide> def version; active_spec.version; end
<ide> def mirrors; active_spec.mirrors; end
<ide>
<ide> def resource(name)
<del> res = @resources[name]
<del> raise ResourceMissingError.new(@name, name) if res.nil?
<del> res
<add> active_spec.resource(name)
<ide> end
<ide>
<ide> def resources
<del> @resources.values
<add> active_spec.resources.values
<ide> end
<ide>
<ide> # if the dir is there, but it's empty we consider it not installed
<ide> def mirror val
<ide> @stable.mirror(val)
<ide> end
<ide>
<del> # Hold any resources defined by this formula
<del> def resources
<del> @resources ||= Hash.new
<del> end
<del>
<ide> # Define a named resource using a SoftwareSpec style block
<ide> def resource name, &block
<del> raise DuplicateResourceError.new(name) if resources.has_key?(name)
<del> resource = Resource.new(name)
<del> resource.instance_eval(&block)
<del> resources[name] = resource
<add> @stable ||= SoftwareSpec.new
<add> @stable.resource(name, &block)
<ide> end
<ide>
<ide> def dependencies
<ide><path>Library/Homebrew/resource.rb
<ide> class Resource
<ide> # XXX: for bottles, address this later
<ide> attr_writer :url, :checksum
<ide>
<del> def initialize name, url=nil, version=nil
<add> def initialize name, url=nil, version=nil, &block
<ide> @name = name
<ide> @url = url
<ide> @version = version
<ide> @mirrors = []
<ide> @specs = {}
<ide> @checksum = nil
<ide> @using = nil
<add> instance_eval(&block) if block_given?
<ide> end
<ide>
<ide> def downloader
<ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide> extend Forwardable
<ide>
<del> def_delegators :@resource, :owner=
<add> attr_reader :resources, :owner
<add>
<ide> def_delegators :@resource, :stage, :fetch
<ide> def_delegators :@resource, :download_strategy, :verify_download_integrity
<ide> def_delegators :@resource, :checksum, :mirrors, :specs, :using, :downloader
<ide> def_delegators :@resource, :url, :version, :mirror, *Checksum::TYPES
<ide>
<ide> def initialize url=nil, version=nil
<ide> @resource = Resource.new(:default, url, version)
<add> @resources = {}
<add> end
<add>
<add> def owner= owner
<add> @resource.owner = owner
<add> resources.each_value { |r| r.owner = owner }
<add> end
<add>
<add> def resource name, &block
<add> if block_given?
<add> raise DuplicateResourceError.new(name) if resources.has_key?(name)
<add> resources[name] = Resource.new(name, &block)
<add> else
<add> resources.fetch(name) { raise ResourceMissingError.new(owner, name) }
<add> end
<ide> end
<ide> end
<ide> | 3 |
Text | Text | fix style importing | 5cef35b8116400d9fdd3e5d4bceaf5a41f4a8565 | <ide><path>examples/with-next-sass/README.md
<ide> This example features:
<ide>
<ide> * An app with next-sass
<ide>
<del>This example uses next-sass without css-modules. The config can be found in `next.config.js`, change `withSass()` to `withSass({cssModules: true})` if you use css-modules. Then in the code, you import the stylesheet as `import style '../styles/style.scss'` and use it like `<div className={style.example}>`.
<add>This example uses next-sass without css-modules. The config can be found in `next.config.js`, change `withSass()` to `withSass({cssModules: true})` if you use css-modules. Then in the code, you import the stylesheet as `import style from '../styles/style.scss'` and use it like `<div className={style.example}>`.
<ide>
<ide> [Learn more](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) | 1 |
Ruby | Ruby | upgrade virtualenv to 16.7.2 | 97cbf43a3dc8db337f6dfd703b9e5055900a4f89 | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<ide> # frozen_string_literal: true
<ide>
<ide> PYTHON_VIRTUALENV_URL =
<del> "https://files.pythonhosted.org/packages/fc/e4" \
<del> "/f0acb4e82acd60f843308112421a41ea70c06bbce51d13fa00736d09a6ae" \
<del> "/virtualenv-16.7.1.tar.gz"
<add> "https://files.pythonhosted.org/packages/a9/8a" \
<add> "/580c7176f01540615c2eb3f3ab5462613b4beac4aa63410be89ecc7b7472" \
<add> "/virtualenv-16.7.2.tar.gz"
<ide> PYTHON_VIRTUALENV_SHA256 =
<del> "d0158c9784570aab78cbb1e4dc59938de128d38e20e5271d9997ada4b417012c"
<add> "909fe0d3f7c9151b2df0a2cb53e55bdb7b0d61469353ff7a49fd47b0f0ab9285" | 1 |
PHP | PHP | fix bug in eloquent model hydration | 720d9de5826cb5a45149715d12b2fa56fe0e7ff4 | <ide><path>laravel/database/eloquent/query.php
<ide> public function hydrate($model, $results, $include = true)
<ide> // we were to pass them in using the constructor or fill methods.
<ide> foreach ($result as $key => $value)
<ide> {
<del> $new->$key = $value;
<add> $new->set_attribute($key, $value);
<ide> }
<ide>
<ide> $new->original = $new->attributes; | 1 |
Javascript | Javascript | fix outputmodule with initial splitchunks | c69e37c39d12c8e3c761c883069d89f90cac817c | <ide><path>lib/esm/ModuleChunkFormatPlugin.js
<ide>
<ide> "use strict";
<ide>
<del>const { ConcatSource, RawSource } = require("webpack-sources");
<add>const { ConcatSource } = require("webpack-sources");
<ide> const { RuntimeGlobals } = require("..");
<ide> const HotUpdateChunk = require("../HotUpdateChunk");
<ide> const Template = require("../Template");
<add>const { getAllChunks } = require("../javascript/ChunkHelpers");
<ide> const {
<ide> getCompilationHooks,
<ide> getChunkFilenameTemplate
<ide> } = require("../javascript/JavascriptModulesPlugin");
<del>const {
<del> generateEntryStartup,
<del> updateHashForEntryStartup
<del>} = require("../javascript/StartupHelpers");
<add>const { updateHashForEntryStartup } = require("../javascript/StartupHelpers");
<ide>
<ide> /** @typedef {import("../Compiler")} Compiler */
<ide>
<ide> class ModuleChunkFormatPlugin {
<ide> }
<ide> )
<ide> .split("/");
<del> const runtimeOutputName = compilation
<del> .getPath(
<del> getChunkFilenameTemplate(
<del> runtimeChunk,
<del> compilation.outputOptions
<del> ),
<del> {
<del> chunk: runtimeChunk,
<del> contentHashType: "javascript"
<del> }
<del> )
<del> .split("/");
<ide>
<ide> // remove filename, we only need the directory
<del> const outputFilename = currentOutputName.pop();
<add> currentOutputName.pop();
<ide>
<del> // remove common parts
<del> while (
<del> currentOutputName.length > 0 &&
<del> runtimeOutputName.length > 0 &&
<del> currentOutputName[0] === runtimeOutputName[0]
<del> ) {
<del> currentOutputName.shift();
<del> runtimeOutputName.shift();
<del> }
<add> const getRelativePath = chunk => {
<add> const baseOutputName = currentOutputName.slice();
<add> const chunkOutputName = compilation
<add> .getPath(
<add> getChunkFilenameTemplate(
<add> chunk,
<add> compilation.outputOptions
<add> ),
<add> {
<add> chunk: chunk,
<add> contentHashType: "javascript"
<add> }
<add> )
<add> .split("/");
<ide>
<del> // create final path
<del> const runtimePath =
<del> (currentOutputName.length > 0
<del> ? "../".repeat(currentOutputName.length)
<del> : "./") + runtimeOutputName.join("/");
<add> // remove common parts
<add> while (
<add> baseOutputName.length > 0 &&
<add> chunkOutputName.length > 0 &&
<add> baseOutputName[0] === chunkOutputName[0]
<add> ) {
<add> baseOutputName.shift();
<add> chunkOutputName.shift();
<add> }
<add> // create final path
<add> return (
<add> (baseOutputName.length > 0
<add> ? "../".repeat(baseOutputName.length)
<add> : "./") + chunkOutputName.join("/")
<add> );
<add> };
<ide>
<ide> const entrySource = new ConcatSource();
<ide> entrySource.add(source);
<ide> entrySource.add(";\n\n// load runtime\n");
<ide> entrySource.add(
<ide> `import __webpack_require__ from ${JSON.stringify(
<del> runtimePath
<del> )};\n`
<del> );
<del> entrySource.add(
<del> `import * as __webpack_self_exports__ from ${JSON.stringify(
<del> "./" + outputFilename
<add> getRelativePath(runtimeChunk)
<ide> )};\n`
<ide> );
<del> entrySource.add(
<del> `${RuntimeGlobals.externalInstallChunk}(__webpack_self_exports__);\n`
<del> );
<del> const startupSource = new RawSource(
<del> generateEntryStartup(
<del> chunkGraph,
<del> runtimeTemplate,
<del> entries,
<del> chunk,
<del> false
<del> )
<add>
<add> const startupSource = new ConcatSource();
<add> startupSource.add(
<add> `var __webpack_exec__ = ${runtimeTemplate.returningFunction(
<add> `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`,
<add> "moduleId"
<add> )}\n`
<ide> );
<add>
<add> const loadedChunks = new Set();
<add> let index = 0;
<add> for (let i = 0; i < entries.length; i++) {
<add> const [module, entrypoint] = entries[i];
<add> const final = i + 1 === entries.length;
<add> const moduleId = chunkGraph.getModuleId(module);
<add> const chunks = getAllChunks(
<add> entrypoint,
<add> runtimeChunk,
<add> undefined
<add> );
<add> for (const chunk of chunks) {
<add> if (loadedChunks.has(chunk)) continue;
<add> loadedChunks.add(chunk);
<add> startupSource.add(
<add> `import * as __webpack_chunk_${index}__ from ${JSON.stringify(
<add> getRelativePath(chunk)
<add> )};\n`
<add> );
<add> startupSource.add(
<add> `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n`
<add> );
<add> index++;
<add> }
<add> startupSource.add(
<add> `${
<add> final ? "var __webpack_exports__ = " : ""
<add> }__webpack_exec__(${JSON.stringify(moduleId)});\n`
<add> );
<add> }
<add>
<ide> entrySource.add(
<ide> hooks.renderStartup.call(
<ide> startupSource,
<ide><path>lib/javascript/ChunkHelpers.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>
<add>"use strict";
<add>
<add>const Entrypoint = require("../Entrypoint");
<add>
<add>/** @typedef {import("../Chunk")} Chunk */
<add>
<add>/**
<add> * @param {Entrypoint} entrypoint a chunk group
<add> * @param {Chunk} excludedChunk1 current chunk which is excluded
<add> * @param {Chunk} excludedChunk2 runtime chunk which is excluded
<add> * @returns {Set<Chunk>} chunks
<add> */
<add>const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => {
<add> const queue = new Set([entrypoint]);
<add> const chunks = new Set();
<add> for (const entrypoint of queue) {
<add> for (const chunk of entrypoint.chunks) {
<add> if (chunk === excludedChunk1) continue;
<add> if (chunk === excludedChunk2) continue;
<add> chunks.add(chunk);
<add> }
<add> for (const parent of entrypoint.parentsIterable) {
<add> if (parent instanceof Entrypoint) queue.add(parent);
<add> }
<add> }
<add> return chunks;
<add>};
<add>exports.getAllChunks = getAllChunks;
<ide><path>lib/javascript/StartupHelpers.js
<ide>
<ide> "use strict";
<ide>
<del>const Entrypoint = require("../Entrypoint");
<ide> const RuntimeGlobals = require("../RuntimeGlobals");
<ide> const Template = require("../Template");
<ide> const { isSubset } = require("../util/SetHelpers");
<add>const { getAllChunks } = require("./ChunkHelpers");
<ide> const { chunkHasJs } = require("./JavascriptModulesPlugin");
<ide>
<ide> /** @typedef {import("../util/Hash")} Hash */
<ide> const { chunkHasJs } = require("./JavascriptModulesPlugin");
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {(string|number)[]} EntryItem */
<ide>
<del>// TODO move to this file to ../javascript/ChunkHelpers.js
<del>
<del>/**
<del> * @param {Entrypoint} entrypoint a chunk group
<del> * @param {Chunk} excludedChunk1 current chunk which is excluded
<del> * @param {Chunk} excludedChunk2 runtime chunk which is excluded
<del> * @returns {Set<Chunk>} chunks
<del> */
<del>const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => {
<del> const queue = new Set([entrypoint]);
<del> const chunks = new Set();
<del> for (const entrypoint of queue) {
<del> for (const chunk of entrypoint.chunks) {
<del> if (chunk === excludedChunk1) continue;
<del> if (chunk === excludedChunk2) continue;
<del> chunks.add(chunk);
<del> }
<del> for (const parent of entrypoint.parentsIterable) {
<del> if (parent instanceof Entrypoint) queue.add(parent);
<del> }
<del> }
<del> return chunks;
<del>};
<del>
<ide> const EXPORT_PREFIX = "var __webpack_exports__ = ";
<ide>
<ide> /**
<ide><path>test/ConfigTestCases.template.js
<ide> const describeCases = config => {
<ide> if (testConfig.beforeExecute) testConfig.beforeExecute();
<ide> const results = [];
<ide> for (let i = 0; i < optionsArr.length; i++) {
<add> const options = optionsArr[i];
<ide> const bundlePath = testConfig.findBundle(i, optionsArr[i]);
<ide> if (bundlePath) {
<ide> filesCount++;
<ide> const describeCases = config => {
<ide> const requireCache = Object.create(null);
<ide> const esmCache = new Map();
<ide> const esmIdentifier = `${category.name}-${testName}-${i}`;
<add> const baseModuleScope = {
<add> console: console,
<add> it: _it,
<add> beforeEach: _beforeEach,
<add> afterEach: _afterEach,
<add> expect,
<add> jest,
<add> __STATS__: jsonStats,
<add> nsObj: m => {
<add> Object.defineProperty(m, Symbol.toStringTag, {
<add> value: "Module"
<add> });
<add> return m;
<add> }
<add> };
<add>
<add> let runInNewContext = false;
<add> if (
<add> options.target === "web" ||
<add> options.target === "webworker"
<add> ) {
<add> baseModuleScope.window = globalContext;
<add> baseModuleScope.self = globalContext;
<add> baseModuleScope.URL = URL;
<add> baseModuleScope.Worker =
<add> require("./helpers/createFakeWorker")({
<add> outputDirectory
<add> });
<add> runInNewContext = true;
<add> }
<add> if (testConfig.moduleScope) {
<add> testConfig.moduleScope(baseModuleScope);
<add> }
<add> const esmContext = vm.createContext(baseModuleScope, {
<add> name: "context for esm"
<add> });
<add>
<ide> // eslint-disable-next-line no-loop-func
<ide> const _require = (
<ide> currentDirectory,
<ide> const describeCases = config => {
<ide> options.experiments &&
<ide> options.experiments.outputModule;
<ide>
<del> let runInNewContext = false;
<del>
<del> const moduleScope = {
<del> console: console,
<del> it: _it,
<del> beforeEach: _beforeEach,
<del> afterEach: _afterEach,
<del> expect,
<del> jest,
<del> __STATS__: jsonStats,
<del> nsObj: m => {
<del> Object.defineProperty(m, Symbol.toStringTag, {
<del> value: "Module"
<del> });
<del> return m;
<del> }
<del> };
<del>
<del> if (
<del> options.target === "web" ||
<del> options.target === "webworker"
<del> ) {
<del> moduleScope.window = globalContext;
<del> moduleScope.self = globalContext;
<del> moduleScope.URL = URL;
<del> moduleScope.Worker =
<del> require("./helpers/createFakeWorker")({
<del> outputDirectory
<del> });
<del> runInNewContext = true;
<del> }
<ide> if (isModule) {
<del> if (testConfig.moduleScope) {
<del> testConfig.moduleScope(moduleScope);
<del> }
<ide> if (!vm.SourceTextModule)
<ide> throw new Error(
<ide> "Running this test requires '--experimental-vm-modules'.\nRun with 'node --experimental-vm-modules node_modules/jest-cli/bin/jest'."
<ide> const describeCases = config => {
<ide> esm = new vm.SourceTextModule(content, {
<ide> identifier: esmIdentifier + "-" + p,
<ide> url: pathToFileURL(p).href + "?" + esmIdentifier,
<del> context:
<del> (parentModule && parentModule.context) ||
<del> vm.createContext(moduleScope, {
<del> name: `context for ${p}`
<del> }),
<add> context: esmContext,
<ide> initializeImportMeta: (meta, module) => {
<ide> meta.url = pathToFileURL(p).href;
<ide> },
<ide> const describeCases = config => {
<ide> exports: {}
<ide> };
<ide> requireCache[p] = m;
<del> Object.assign(moduleScope, {
<add> const moduleScope = {
<add> ...baseModuleScope,
<ide> require: _require.bind(
<ide> null,
<ide> path.dirname(p),
<ide> const describeCases = config => {
<ide> __dirname: path.dirname(p),
<ide> __filename: p,
<ide> _globalAssign: { expect }
<del> });
<add> };
<ide> if (testConfig.moduleScope) {
<ide> testConfig.moduleScope(moduleScope);
<ide> }
<ide> const describeCases = config => {
<ide> results.push(
<ide> _require(
<ide> outputDirectory,
<del> optionsArr[i],
<add> options,
<ide> "./" + bundlePathItem
<ide> )
<ide> );
<ide> }
<ide> } else {
<ide> results.push(
<del> _require(outputDirectory, optionsArr[i], bundlePath)
<add> _require(outputDirectory, options, bundlePath)
<ide> );
<ide> }
<ide> }
<ide><path>test/configCases/module/runtime-chunk/test.config.js
<ide> module.exports = {
<ide> findBundle: function () {
<del> return ["./runtime.js", "./main.js"];
<add> return ["./runtime.mjs", "./main.mjs"];
<ide> }
<ide> };
<ide><path>test/configCases/module/runtime-chunk/webpack.config.js
<ide> /** @type {import("../../../../").Configuration} */
<ide> module.exports = {
<ide> output: {
<del> filename: "[name].js"
<add> filename: "[name].mjs"
<ide> },
<del> target: "web",
<add> target: ["web", "es2020"],
<ide> experiments: {
<ide> outputModule: true
<ide> },
<ide><path>test/configCases/module/split-chunks/index.js
<add>import value from "./separate";
<add>import { test as t } from "external-self";
<add>
<add>it("should compile", () => {
<add> expect(value).toBe(42);
<add>});
<add>it("should circular depend on itself external", () => {
<add> expect(test()).toBe(42);
<add> expect(t()).toBe(42);
<add>});
<add>
<add>function test() {
<add> return 42;
<add>}
<add>
<add>export { test };
<ide><path>test/configCases/module/split-chunks/separate.js
<add>export default 42;
<ide><path>test/configCases/module/split-chunks/test.config.js
<add>module.exports = {
<add> findBundle: function () {
<add> return ["./runtime.mjs", "./separate.mjs", "./main.mjs"];
<add> }
<add>};
<ide><path>test/configCases/module/split-chunks/webpack.config.js
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> output: {
<add> filename: "[name].mjs",
<add> library: {
<add> type: "module"
<add> }
<add> },
<add> target: ["web", "es2020"],
<add> experiments: {
<add> outputModule: true
<add> },
<add> optimization: {
<add> minimize: true,
<add> runtimeChunk: "single",
<add> splitChunks: {
<add> cacheGroups: {
<add> separate: {
<add> test: /separate/,
<add> chunks: "all",
<add> filename: "separate.mjs",
<add> enforce: true
<add> }
<add> }
<add> }
<add> },
<add> externals: {
<add> "external-self": "./main.mjs"
<add> }
<add>}; | 10 |
Javascript | Javascript | convert callback to arrow function | afab340e6708a86d8573d44041704873cf558d0e | <ide><path>test/pummel/test-net-pause.js
<ide> const server = net.createServer((connection) => {
<ide> server.on('listening', () => {
<ide> const client = net.createConnection(common.PORT);
<ide> client.setEncoding('ascii');
<del> client.on('data', function(d) {
<add> client.on('data', (d) => {
<ide> console.log(d);
<ide> recv += d;
<ide> }); | 1 |
Text | Text | remove unneeded new in buffer example | 951dbc045aebbe1f7eff12cedabce1179544dc75 | <ide><path>doc/api/buffer.md
<ide> a `Buffer` is that in this case one needs to specify the `byteOffset` correctly:
<ide> import { Buffer } from 'buffer';
<ide>
<ide> // Create a buffer smaller than `Buffer.poolSize`.
<del>const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
<add>const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
<ide>
<ide> // When casting the Node.js Buffer to an Int8Array, use the byteOffset
<ide> // to refer only to the part of `nodeBuffer.buffer` that contains the memory
<ide> new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
<ide> const { Buffer } = require('buffer');
<ide>
<ide> // Create a buffer smaller than `Buffer.poolSize`.
<del>const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
<add>const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
<ide>
<ide> // When casting the Node.js Buffer to an Int8Array, use the byteOffset
<ide> // to refer only to the part of `nodeBuffer.buffer` that contains the memory | 1 |
Javascript | Javascript | fix crash when calling __proto__.write() | 24fc302eadf64d2518733a2ae40355916e6990f7 | <ide><path>lib/string_decoder.js
<ide> const {
<ide> const internalUtil = require('internal/util');
<ide> const {
<ide> ERR_INVALID_ARG_TYPE,
<add> ERR_INVALID_THIS,
<ide> ERR_UNKNOWN_ENCODING
<ide> } = require('internal/errors').codes;
<ide> const isEncoding = Buffer[internalUtil.kIsEncodingSymbol];
<ide> StringDecoder.prototype.write = function write(buf) {
<ide> throw new ERR_INVALID_ARG_TYPE('buf',
<ide> ['Buffer', 'TypedArray', 'DataView'],
<ide> buf);
<add> if (!this[kNativeDecoder]) {
<add> throw new ERR_INVALID_THIS('StringDecoder');
<add> }
<ide> return decode(this[kNativeDecoder], buf);
<ide> };
<ide>
<ide><path>test/parallel/test-string-decoder.js
<ide> if (common.enoughTestMem) {
<ide> );
<ide> }
<ide>
<add>assert.throws(
<add> () => new StringDecoder('utf8').__proto__.write(Buffer.from('abc')), // eslint-disable-line no-proto
<add> {
<add> code: 'ERR_INVALID_THIS',
<add> }
<add>);
<add>
<ide> // Test verifies that StringDecoder will correctly decode the given input
<ide> // buffer with the given encoding to the expected output. It will attempt all
<ide> // possible ways to write() the input buffer, see writeSequences(). The | 2 |
Javascript | Javascript | add shallow support to link | 4c52ea1f70d3636887555b95c9c3c0999fbb102c | <ide><path>lib/link.js
<ide> export default class Link extends Component {
<ide>
<ide> return null
<ide> }
<del> ]).isRequired
<add> ]).isRequired,
<add> shallow: PropTypes.bool
<ide> }
<ide>
<ide> componentWillReceiveProps (nextProps) {
<ide> export default class Link extends Component {
<ide> return
<ide> }
<ide>
<add> let { shallow } = this.props
<ide> let { href, as } = this
<ide>
<ide> if (!isLocal(href)) {
<ide> export default class Link extends Component {
<ide> const changeMethod = replace ? 'replace' : 'push'
<ide>
<ide> // straight up redirect
<del> Router[changeMethod](href, as)
<add> Router[changeMethod](href, as, { shallow })
<ide> .then((success) => {
<ide> if (!success) return
<ide> if (scroll) window.scrollTo(0, 0) | 1 |
Javascript | Javascript | add ngattrsize as argument | b9d3185e52292b1d57a7b19800db73accb2f8ff2 | <ide><path>src/ng/directive/ngOptions.js
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> *
<ide> *
<ide> * @param {string} ngModel Assignable AngularJS expression to data-bind to.
<del> * @param {string=} name Property name of the form under which the control is published.
<del> * @param {string=} required The control is considered valid only if value is entered.
<del> * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
<del> * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
<del> * `required` when you want to data-bind to the `required` attribute.
<del> * @param {comprehension_expression=} ngOptions in one of the following forms:
<add> * @param {comprehension_expression} ngOptions in one of the following forms:
<ide> *
<ide> * * for array data sources:
<ide> * * `label` **`for`** `value` **`in`** `array`
<ide> var ngOptionsMinErr = minErr('ngOptions');
<ide> * used to identify the objects in the array. The `trackexpr` will most likely refer to the
<ide> * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
<ide> * even when the options are recreated (e.g. reloaded from the server).
<add> * @param {string=} name Property name of the form under which the control is published.
<add> * @param {string=} required The control is considered valid only if value is entered.
<add> * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
<add> * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
<add> * `required` when you want to data-bind to the `required` attribute.
<add> * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
<add> * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
<ide> *
<ide> * @example
<ide> <example module="selectExample" name="select">
<ide><path>src/ng/directive/select.js
<ide> var SelectController =
<ide> * interaction with the select element.
<ide> * @param {string=} ngOptions sets the options that the select is populated with and defines what is
<ide> * set on the model on selection. See {@link ngOptions `ngOptions`}.
<add> * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
<add> * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
<ide> *
<ide> * @example
<ide> * ### Simple `select` elements with static options | 2 |
Text | Text | fix inconsistency in documentation for building | a456775efa9ea284dd1a1d37602699bfb5bbd561 | <ide><path>BUILDING.md
<ide> If you are running tests prior to submitting a Pull Request, the recommended
<ide> command is:
<ide>
<ide> ```console
<del>$ make test
<add>$ make -j4 test
<ide> ```
<ide>
<del>`make test` does a full check on the codebase, including running linters and
<add>`make -j4 test` does a full check on the codebase, including running linters and
<ide> documentation tests.
<ide>
<ide> Optionally, continue below. | 1 |
Ruby | Ruby | fix elapsed time calculations | dda9452314bb904a3e2c850bd23f118eb80e3356 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def no_wait_poll
<ide> def wait_poll(timeout)
<ide> @num_waiting += 1
<ide>
<del> t0 = Time.now
<add> t0 = Concurrent.monotonic_time
<ide> elapsed = 0
<ide> loop do
<ide> ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
<ide> def wait_poll(timeout)
<ide>
<ide> return remove if any?
<ide>
<del> elapsed = Time.now - t0
<add> elapsed = Concurrent.monotonic_time - t0
<ide> if elapsed >= timeout
<ide> msg = "could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use" %
<ide> [timeout, elapsed]
<ide> def attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout =
<ide> end
<ide>
<ide> newly_checked_out = []
<del> timeout_time = Time.now + (@checkout_timeout * 2)
<add> timeout_time = Concurrent.monotonic_time + (@checkout_timeout * 2)
<ide>
<ide> @available.with_a_bias_for(Thread.current) do
<ide> loop do
<ide> synchronize do
<ide> return if collected_conns.size == @connections.size && @now_connecting == 0
<del> remaining_timeout = timeout_time - Time.now
<add> remaining_timeout = timeout_time - Concurrent.monotonic_time
<ide> remaining_timeout = 0 if remaining_timeout < 0
<ide> conn = checkout_for_exclusive_access(remaining_timeout)
<ide> collected_conns << conn
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def clear_cache!
<ide>
<ide> def explain(arel, binds = [])
<ide> sql = "EXPLAIN #{to_sql(arel, binds)}"
<del> start = Time.now
<add> start = Concurrent.monotonic_time
<ide> result = exec_query(sql, "EXPLAIN", binds)
<del> elapsed = Time.now - start
<add> elapsed = Concurrent.monotonic_time - start
<ide>
<ide> MySQL::ExplainPrettyPrinter.new.pp(result, elapsed)
<ide> end
<ide><path>activesupport/lib/active_support/cache/memory_store.rb
<ide> def prune(target_size, max_time = nil)
<ide> return if pruning?
<ide> @pruning = true
<ide> begin
<del> start_time = Time.now
<add> start_time = Concurrent.monotonic_time
<ide> cleanup
<ide> instrument(:prune, target_size, from: @cache_size) do
<ide> keys = synchronize { @key_access.keys.sort { |a, b| @key_access[a].to_f <=> @key_access[b].to_f } }
<ide> keys.each do |key|
<ide> delete_entry(key, options)
<del> return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time)
<add> return if @cache_size <= target_size || (max_time && Concurrent.monotonic_time - start_time > max_time)
<ide> end
<ide> end
<ide> ensure
<ide><path>activesupport/lib/active_support/notifications/instrumenter.rb
<ide> def parent_of?(event)
<ide>
<ide> private
<ide> def now
<del> Process.clock_gettime(Process::CLOCK_MONOTONIC)
<add> Concurrent.monotonic_time
<ide> end
<ide>
<ide> if clock_gettime_supported? | 4 |
Text | Text | fix truncated line in the i18n edge guide | c7d39f2a2e377c020e57747b70502c51fd0b6349 | <ide><path>guides/source/i18n.md
<ide> This means, that in the `:en` locale, the key _hello_ will map to the _Hello wor
<ide>
<ide> The I18n library will use **English** as a **default locale**, i.e. if you don't set a different locale, `:en` will be used for looking up translations.
<ide>
<del>NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize2](ht)
<add>NOTE: The i18n library takes a **pragmatic approach** to locale keys (after [some discussion](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like `:en`, `:pl`, not the _region_ part, like `:en-US` or `:en-GB`, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as `:cs`, `:th` or `:es` (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the `:en-US` locale you would have $ as a currency symbol, while in `:en-GB`, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a `:en-GB` dictionary. Various [Rails I18n plugins](http://rails-i18n.org/wiki) such as [Globalize2](https://github.com/joshmh/globalize2/tree/master) may help you implement it.
<ide>
<ide> The **translations load path** (`I18n.load_path`) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
<ide> | 1 |
Ruby | Ruby | add dependencies to 'brew info' output | 9d290b450255ad8160f2dfc75181bfdd80bbf3b7 | <ide><path>Library/Homebrew/brew.h.rb
<ide> def info name
<ide> puts "#{f.name} #{f.version}"
<ide> puts f.homepage
<ide>
<add> if not f.deps.empty?
<add> puts "Depends on: #{f.deps.join(', ')}"
<add> end
<add>
<ide> if f.prefix.parent.directory?
<ide> kids=f.prefix.parent.children
<ide> kids.each do |keg| | 1 |
Text | Text | add advanced test helpers docs to guides | d45b74e89708bb26c68f04e17090eb1c56898ed8 | <ide><path>guides/source/testing.md
<ide> class ProfileControllerTest < ActionDispatch::IntegrationTest
<ide> end
<ide> ```
<ide>
<add>#### Using Separate Files
<add>
<add>If you find your helpers are cluttering `test_helper.rb`, you can extract them into separate files. One good place to store them is `lib/test`.
<add>
<add>```ruby
<add># lib/test/multiple_assertions.rb
<add>module MultipleAssertions
<add> def assert_multiple_of_fourty_two(number)
<add> assert (number % 42 == 0), 'expected #{number} to be a multiple of 42'
<add> end
<add>end
<add>```
<add>
<add>These helpers can then be explicitly required as needed and included as needed
<add>
<add>```ruby
<add>require 'test_helper'
<add>require 'test/multiple_assertions'
<add>
<add>class NumberTest < ActiveSupport::TestCase
<add> include MultipleAssertions
<add>
<add> test '420 is a multiple of fourty two' do
<add> assert_multiple_of_fourty_two 420
<add> end
<add>end
<add>```
<add>
<add>or they can continue to be included directly into the relevant parent classes
<add>
<add>```ruby
<add># test/test_helper.rb
<add>require 'test/sign_in_helper'
<add>
<add>class ActionDispatch::IntegrationTest
<add> include SignInHelper
<add>end
<add>```
<add>
<add>#### Eagerly Requiring Helpers
<add>
<add>You may find it convenient to eagerly require helpers in `test_helper.rb` so your test files have implicit access to them. This can be accomplished using globbing, as follows
<add>
<add>```ruby
<add># test/test_helper.rb
<add>Dir[Rails.root.join('lib', 'test', '**', '*.rb')].each { |file| require file }
<add>```
<add>
<add>This has the downside of increasing the boot-up time, as opposed to manually requiring only the necessary files in your individual tests.
<add>
<ide> Testing Routes
<ide> --------------
<ide> | 1 |
Go | Go | fix hostname support for compose file | d0117238fa74ea75cdec7b9205620c59bafc4508 | <ide><path>daemon/cluster/executor/container/container.go
<ide> func (c *containerConfig) config() *enginecontainer.Config {
<ide> User: c.spec().User,
<ide> Hostname: c.spec().Hostname,
<ide> Env: c.spec().Env,
<add> Hostname: c.spec().Hostname,
<ide> WorkingDir: c.spec().Dir,
<ide> Image: c.image(),
<ide> Volumes: c.volumes(), | 1 |
Python | Python | upgrade `moto` library to version 3.0 | de29eb6122cd2e66561d6b9fa99bb730cdfa3053 | <ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'jira',
<ide> 'jsondiff',
<ide> 'mongomock',
<del> # Moto3 is limited for unknown reason
<del> # TODO: attempt to remove the limitation
<del> 'moto~=2.2,>=2.2.12',
<add> 'moto>=3.0.3',
<ide> 'parameterized',
<ide> 'paramiko',
<ide> 'pipdeptree',
<ide><path>tests/providers/amazon/aws/hooks/test_kinesis.py
<ide> def test_insert_batch_records_kinesis_firehose(self):
<ide> )
<ide>
<ide> stream_arn = response['DeliveryStreamARN']
<del> assert stream_arn == "arn:aws:firehose:us-east-1:123456789012:/delivery_stream/test_airflow"
<add> assert stream_arn == "arn:aws:firehose:us-east-1:123456789012:deliverystream/test_airflow"
<ide>
<ide> records = [{"Data": str(uuid.uuid4())} for _ in range(100)]
<ide> | 2 |
Javascript | Javascript | use the toequaloneof matcher in jqlite tests | 121f64936e82c92c6ec055b07be7511cc1c2834a | <ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function() {
<ide> '<option>test 2</option>' +
<ide> '</select>').val()).toEqual(['test 1']);
<ide>
<del> // In jQuery >= 3.0 .val() on select[multiple] with no selected options returns an
<del> // empty array, not null.
<del> // See https://github.com/jquery/jquery/issues/2562 for more details.
<del> // jqLite will align with jQuery 3.0 behavior in Angular 1.6.
<del> var val;
<del> if (_jqLiteMode || isJQuery2x()) {
<del> val = null;
<del> } else {
<del> val = [];
<del> }
<del>
<add> // In jQuery < 3.0 .val() on select[multiple] with no selected options returns an
<add> // null instead of an empty array.
<ide> expect(jqLite(
<ide> '<select multiple>' +
<ide> '<option>test 1</option>' +
<ide> '<option>test 2</option>' +
<del> '</select>').val()).toEqual(val);
<add> '</select>').val()).toEqualOneOf(null, []);
<ide> });
<ide> });
<ide> | 1 |
Python | Python | use tensorflow leaky_relu op for efficiency | f699346386e2de5a76fbed1f1c2d16c6fa1d9000 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def relu(x, alpha=0., max_value=None):
<ide> A tensor.
<ide> """
<ide> if alpha != 0.:
<del> negative_part = tf.nn.relu(-x)
<del> x = tf.nn.relu(x)
<add> x = tf.nn.leaky_relu(x, alpha)
<add> else:
<add> x = tf.nn.relu(x)
<add>
<ide> if max_value is not None:
<ide> max_value = _to_tensor(max_value, x.dtype.base_dtype)
<del> zero = _to_tensor(0., x.dtype.base_dtype)
<del> x = tf.clip_by_value(x, zero, max_value)
<del> if alpha != 0.:
<del> alpha = _to_tensor(alpha, x.dtype.base_dtype)
<del> x -= alpha * negative_part
<add> x = tf.minimum(x, max_value)
<ide> return x
<ide>
<ide> | 1 |
PHP | PHP | add keys method to messagebag | 01d5d7465ee5975352b953cbe63131612b1a0d27 | <ide><path>src/Illuminate/Support/MessageBag.php
<ide> public function __construct(array $messages = array())
<ide> }
<ide> }
<ide>
<add> /**
<add> * Get the keys present in the message bag.
<add> *
<add> * @return array
<add> */
<add> public function keys()
<add> {
<add> return array_keys($this->messages);
<add> }
<add>
<ide> /**
<ide> * Add a message to the bag.
<ide> * | 1 |
Python | Python | correct error in description of ndarray.base | a6c974489b753437dc5929326d4c320d39f26c08 | <ide><path>numpy/doc/subclassing.py
<ide> def __array_wrap__(self, arr, context=None):
<ide> True
<ide> >>> # Take a view of a view
<ide> >>> v2 = v1[1:]
<del>>>> # base points to the view it derived from
<del>>>> v2.base is v1
<add>>>> # base points to the original array that it was derived from
<add>>>> v2.base is arr
<ide> True
<ide>
<ide> In general, if the array owns its own memory, as for ``arr`` in this | 1 |
Javascript | Javascript | improve performance for sync write finishes | 2205f85b2caadee425a0a86bd8cc3bcb889e4bfe | <ide><path>benchmark/streams/writable-manywrites.js
<ide> const common = require('../common');
<ide> const Writable = require('stream').Writable;
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> n: [2e6]
<add> n: [2e6],
<add> sync: ['yes', 'no']
<ide> });
<ide>
<del>function main({ n }) {
<add>function main({ n, sync }) {
<ide> const b = Buffer.allocUnsafe(1024);
<ide> const s = new Writable();
<add> sync = sync === 'yes';
<ide> s._write = function(chunk, encoding, cb) {
<del> cb();
<add> if (sync)
<add> cb();
<add> else
<add> process.nextTick(cb);
<ide> };
<ide>
<ide> bench.start();
<ide><path>lib/_stream_writable.js
<ide> function WritableState(options, stream, isDuplex) {
<ide> // The amount that is being written when _write is called.
<ide> this.writelen = 0;
<ide>
<add> // Storage for data passed to the afterWrite() callback in case of
<add> // synchronous _write() completion.
<add> this.afterWriteTickInfo = null;
<add>
<ide> this.bufferedRequest = null;
<ide> this.lastBufferedRequest = null;
<ide>
<ide> function onwrite(stream, er) {
<ide> }
<ide>
<ide> if (sync) {
<del> process.nextTick(afterWrite, stream, state, cb);
<add> // It is a common case that the callback passed to .write() is always
<add> // the same. In that case, we do not schedule a new nextTick(), but rather
<add> // just increase a counter, to improve performance and avoid memory
<add> // allocations.
<add> if (state.afterWriteTickInfo !== null &&
<add> state.afterWriteTickInfo.cb === cb) {
<add> state.afterWriteTickInfo.count++;
<add> } else {
<add> state.afterWriteTickInfo = { count: 1, cb, stream, state };
<add> process.nextTick(afterWriteTick, state.afterWriteTickInfo);
<add> }
<ide> } else {
<del> afterWrite(stream, state, cb);
<add> afterWrite(stream, state, 1, cb);
<ide> }
<ide> }
<ide> }
<ide>
<del>function afterWrite(stream, state, cb) {
<add>function afterWriteTick({ stream, state, count, cb }) {
<add> state.afterWriteTickInfo = null;
<add> return afterWrite(stream, state, count, cb);
<add>}
<add>
<add>function afterWrite(stream, state, count, cb) {
<ide> const needDrain = !state.ending && !stream.destroyed && state.length === 0 &&
<ide> state.needDrain;
<ide> if (needDrain) {
<ide> state.needDrain = false;
<ide> stream.emit('drain');
<ide> }
<del> state.pendingcb--;
<del> cb();
<add>
<add> while (count-- > 0) {
<add> state.pendingcb--;
<add> cb();
<add> }
<add>
<ide> finishMaybe(stream, state);
<ide> }
<ide>
<ide><path>test/parallel/test-stream-writable-samecb-singletick.js
<add>'use strict';
<add>const common = require('../common');
<add>const { Console } = require('console');
<add>const { Writable } = require('stream');
<add>const async_hooks = require('async_hooks');
<add>
<add>// Make sure that repeated calls to console.log(), and by extension
<add>// stream.write() for the underlying stream, allocate exactly 1 tick object.
<add>// At the time of writing, that is enough to ensure a flat memory profile
<add>// from repeated console.log() calls, rather than having callbacks pile up
<add>// over time, assuming that data can be written synchronously.
<add>// Refs: https://github.com/nodejs/node/issues/18013
<add>// Refs: https://github.com/nodejs/node/issues/18367
<add>
<add>const checkTickCreated = common.mustCall();
<add>
<add>async_hooks.createHook({
<add> init(id, type, triggerId, resoure) {
<add> if (type === 'TickObject') checkTickCreated();
<add> }
<add>}).enable();
<add>
<add>const console = new Console(new Writable({
<add> write: common.mustCall((chunk, encoding, cb) => {
<add> cb();
<add> }, 100)
<add>}));
<add>
<add>for (let i = 0; i < 100; i++)
<add> console.log(i); | 3 |
Ruby | Ruby | bring #reorder back | fb215110401c70cfc7013c6e2ad5753fa4e374e9 | <ide><path>activerecord/lib/active_record/base.rb
<ide> class Base
<ide> class << self # Class methods
<ide> delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped
<ide> delegate :find_each, :find_in_batches, :to => :scoped
<del> delegate :select, :group, :order, :except, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
<add> delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
<ide> delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
<ide>
<ide> # Executes a custom SQL query against your database and returns all the results. The results will
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def order(*args)
<ide> relation
<ide> end
<ide>
<add> def reorder(*args)
<add> except(:order).order(args)
<add> end
<add>
<ide> def joins(*args)
<ide> return self if args.compact.blank?
<ide>
<ide><path>activerecord/test/cases/relation_scoping_test.rb
<ide> def test_scope_overwrites_default
<ide> assert_equal expected, received
<ide> end
<ide>
<del> def test_except_and_order_overrides_default_scope_order
<add> def test_reorder_overrides_default_scope_order
<ide> expected = Developer.order('name DESC').collect { |dev| dev.name }
<del> received = DeveloperOrderedBySalary.except(:order).order('name DESC').collect { |dev| dev.name }
<add> received = DeveloperOrderedBySalary.reorder('name DESC').collect { |dev| dev.name }
<ide> assert_equal expected, received
<ide> end
<ide>
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_finding_with_order_concatenated
<ide> assert_equal topics(:fourth).title, topics.first.title
<ide> end
<ide>
<add> def test_finding_with_reorder
<add> topics = Topic.order('author_name').order('title').reorder('id').all
<add> topics_titles = topics.map{ |t| t.title }
<add> assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day'], topics_titles
<add> end
<add>
<ide> def test_finding_with_order_and_take
<ide> entrants = Entrant.order("id ASC").limit(2).to_a
<ide> | 4 |
Ruby | Ruby | fix update_version_rb task | 7142e924b4ea366ef4ba067cd7afe6581c98b4c4 | <ide><path>tasks/release.rb
<ide> file = Dir[glob].first
<ide> ruby = File.read(file)
<ide>
<del> major, minor, tiny, pre = version.split('.')
<del> pre = pre ? pre.inspect : "nil"
<del>
<del> ruby.gsub!(/^(\s*)MAJOR = .*?$/, "\\1MAJOR = #{major}")
<del> raise "Could not insert MAJOR in #{file}" unless $1
<del>
<del> ruby.gsub!(/^(\s*)MINOR = .*?$/, "\\1MINOR = #{minor}")
<del> raise "Could not insert MINOR in #{file}" unless $1
<del>
<del> ruby.gsub!(/^(\s*)TINY = .*?$/, "\\1TINY = #{tiny}")
<del> raise "Could not insert TINY in #{file}" unless $1
<del>
<del> ruby.gsub!(/^(\s*)PRE = .*?$/, "\\1PRE = #{pre}")
<del> raise "Could not insert PRE in #{file}" unless $1
<add> ruby.gsub!(/^(\s*)Gem::Version\.new .*?$/, "\\1Gem::Version.new \"#{version}\"")
<add> raise "Could not insert Gem::Version in #{file}" unless $1
<ide>
<ide> File.open(file, 'w') { |f| f.write ruby }
<ide> end | 1 |
Ruby | Ruby | remove some lasigns | 05168067609b867eb77a99ff3eb39250d22ae046 | <ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb
<ide> def reset_primary_key #:nodoc:
<ide> end
<ide>
<ide> def get_primary_key(base_name) #:nodoc:
<del> key = 'id'
<ide> case primary_key_prefix_type
<del> when :table_name
<del> key = base_name.to_s.foreign_key(false)
<del> when :table_name_with_underscore
<del> key = base_name.to_s.foreign_key
<add> when :table_name
<add> base_name.to_s.foreign_key(false)
<add> when :table_name_with_underscore
<add> base_name.to_s.foreign_key
<add> else
<add> 'id'
<ide> end
<del> key
<ide> end
<ide>
<ide> # Sets the name of the primary key column to use to the given value, | 1 |
Ruby | Ruby | parse version from sdksettings.json | c77c9422915773c33c33ebba0d913c4f5ca29c57 | <ide><path>Library/Homebrew/os/mac/sdk.rb
<ide> def sdk_paths
<ide>
<ide> # Use unversioned SDK path on Big Sur to avoid issues such as:
<ide> # https://github.com/Homebrew/homebrew-core/issues/67075
<del> if OS::Mac.version >= :big_sur
<del> sdk_path = File.join(sdk_prefix, "MacOSX.sdk")
<del> version = OS::Mac.full_version
<del> paths[version] = sdk_path if File.directory?(sdk_path)
<add> sdk_path = File.join(sdk_prefix, "MacOSX.sdk")
<add> if OS::Mac.version >= :big_sur && File.directory?(sdk_path)
<add> sdk_settings = File.join(sdk_path, "SDKSettings.json")
<add> version = JSON.parse(File.read(sdk_settings))["Version"] if File.exist?(sdk_settings)
<add> paths[OS::Mac::Version.new(version)] = sdk_path if version.present?
<ide> end
<ide>
<ide> paths | 1 |
Javascript | Javascript | add animated param in listview#scrollto | 9506e5afc7844a45d3029c209ae5809c5f4c5e44 | <ide><path>Libraries/CustomComponents/ListView/ListView.js
<ide> var ListView = React.createClass({
<ide> this.refs[SCROLLVIEW_REF].getScrollResponder();
<ide> },
<ide>
<del> scrollTo: function(destY, destX) {
<del> this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0);
<add> scrollTo: function(destY, destX, animated = true) {
<add> this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0, animated);
<ide> },
<ide>
<ide> setNativeProps: function(props) {
<ide> var ListView = React.createClass({
<ide> this.scrollProperties.visibleLength = visibleLength;
<ide> this._updateVisibleRows();
<ide> this._renderMoreRowsIfNeeded();
<del> }
<add> }
<ide> this.props.onLayout && this.props.onLayout(event);
<ide> },
<ide>
<ide> var ListView = React.createClass({
<ide> this._maybeCallOnEndReached();
<ide> return;
<ide> }
<del>
<add>
<ide> var distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties);
<ide> if (distanceFromEnd < this.props.scrollRenderAheadDistance) {
<ide> this._pageInNewRows(); | 1 |
Javascript | Javascript | fix linting errors | e5844314e3b644e52d6d73b24dc66b6e1a508094 | <ide><path>examples/with-redux/pages/index.js
<ide> import React from 'react'
<del>import { reducer, initStore, startClock } from '../store'
<del>import withRedux from 'next-redux-wrapper';
<add>import { initStore, startClock } from '../store'
<add>import withRedux from 'next-redux-wrapper'
<ide> import Page from '../components/Page'
<ide>
<ide> class Counter extends React.Component {
<ide> class Counter extends React.Component {
<ide> }
<ide> }
<ide>
<del>export default withRedux(initStore)(Counter)
<ide>\ No newline at end of file
<add>export default withRedux(initStore)(Counter)
<ide><path>examples/with-redux/pages/other.js
<ide> import React from 'react'
<del>import { reducer, initStore, startClock } from '../store'
<del>import withRedux from 'next-redux-wrapper';
<add>import { initStore, startClock } from '../store'
<add>import withRedux from 'next-redux-wrapper'
<ide> import Page from '../components/Page'
<ide>
<ide> class Counter extends React.Component {
<ide> class Counter extends React.Component {
<ide> }
<ide> }
<ide>
<del>export default withRedux(initStore)(Counter)
<ide>\ No newline at end of file
<add>export default withRedux(initStore)(Counter) | 2 |
PHP | PHP | build settings in bootstrap | 89d3221adcce65dbd7ab13fcc200676963f4b8ed | <ide><path>app/Config/bootstrap.php
<ide> * The settings below can be used to set additional paths to models, views and controllers.
<ide> *
<ide> * App::build(array(
<del> * 'Plugin' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'),
<del> * 'Model' => array('/full/path/to/models/', '/next/full/path/to/models/'),
<del> * 'View' => array('/full/path/to/views/', '/next/full/path/to/views/'),
<del> * 'Controller' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),
<del> * 'Model/Datasource' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),
<del> * 'Model/Behavior' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),
<del> * 'Controller/Component' => array('/full/path/to/components/', '/next/full/path/to/components/'),
<del> * 'View/Helper' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'),
<del> * 'Vendor' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'),
<del> * 'Console/Command' => array('/full/path/to/shells/', '/next/full/path/to/shells/'),
<del> * 'Locale' => array('/full/path/to/locale/', '/next/full/path/to/locale/')
<add> * 'Model' => array('/path/to/models', '/next/path/to/models'),
<add> * 'Model/Behavior' => array('/path/to/behaviors', '/next/path/to/behaviors'),
<add> * 'Model/Datasource' => array('/path/to/datasources', '/next/path/to/datasources'),
<add> * 'Model/Datasource/Database' => array('/path/to/databases', '/next/path/to/database'),
<add> * 'Model/Datasource/Session' => array('/path/to/sessions', '/next/path/to/sessions'),
<add> * 'Controller' => array('/path/to/controllers', '/next/path/to/controllers'),
<add> * 'Controller/Component' => array('/path/to/components', '/next/path/to/components'),
<add> * 'Controller/Component/Auth' => array('/path/to/auths', '/next/path/to/auths'),
<add> * 'Controller/Component/Acl' => array('/path/to/acls', '/next/path/to/acls'),
<add> * 'View' => array('/path/to/views', '/next/path/to/views'),
<add> * 'View/Helper' => array('/path/to/helpers', '/next/path/to/helpers'),
<add> * 'Console' => array('/path/to/consoles', '/next/path/to/consoles'),
<add> * 'Console/Command' => array('/path/to/commands', '/next/path/to/commands'),
<add> * 'Console/Command/Task' => array('/path/to/tasks', '/next/path/to/tasks'),
<add> * 'Lib' => array('/path/to/libs', '/next/path/to/libs'),
<add> * 'Locale' => array('/path/to/locales', '/next/path/to/locales'),
<add> * 'Vendor' => array('/path/to/vendors', '/next/path/to/vendors'),
<add> * 'Plugin' => array('/path/to/plugins', '/next/path/to/plugins'),
<ide> * ));
<ide> *
<ide> */
<ide><path>lib/Cake/Console/Templates/skel/Config/bootstrap.php
<ide> * The settings below can be used to set additional paths to models, views and controllers.
<ide> *
<ide> * App::build(array(
<del> * 'Plugin' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'),
<del> * 'Model' => array('/full/path/to/models/', '/next/full/path/to/models/'),
<del> * 'View' => array('/full/path/to/views/', '/next/full/path/to/views/'),
<del> * 'Controller' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),
<del> * 'Model/Datasource' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),
<del> * 'Model/Behavior' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),
<del> * 'Controller/Component' => array('/full/path/to/components/', '/next/full/path/to/components/'),
<del> * 'View/Helper' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'),
<del> * 'Vendor' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'),
<del> * 'Console/Command' => array('/full/path/to/shells/', '/next/full/path/to/shells/'),
<del> * 'Locale' => array('/full/path/to/locale/', '/next/full/path/to/locale/')
<add> * 'Model' => array('/path/to/models', '/next/path/to/models'),
<add> * 'Model/Behavior' => array('/path/to/behaviors', '/next/path/to/behaviors'),
<add> * 'Model/Datasource' => array('/path/to/datasources', '/next/path/to/datasources'),
<add> * 'Model/Datasource/Database' => array('/path/to/databases', '/next/path/to/database'),
<add> * 'Model/Datasource/Session' => array('/path/to/sessions', '/next/path/to/sessions'),
<add> * 'Controller' => array('/path/to/controllers', '/next/path/to/controllers'),
<add> * 'Controller/Component' => array('/path/to/components', '/next/path/to/components'),
<add> * 'Controller/Component/Auth' => array('/path/to/auths', '/next/path/to/auths'),
<add> * 'Controller/Component/Acl' => array('/path/to/acls', '/next/path/to/acls'),
<add> * 'View' => array('/path/to/views', '/next/path/to/views'),
<add> * 'View/Helper' => array('/path/to/helpers', '/next/path/to/helpers'),
<add> * 'Console' => array('/path/to/consoles', '/next/path/to/consoles'),
<add> * 'Console/Command' => array('/path/to/commands', '/next/path/to/commands'),
<add> * 'Console/Command/Task' => array('/path/to/tasks', '/next/path/to/tasks'),
<add> * 'Lib' => array('/path/to/libs', '/next/path/to/libs'),
<add> * 'Locale' => array('/path/to/locales', '/next/path/to/locales'),
<add> * 'Vendor' => array('/path/to/vendors', '/next/path/to/vendors'),
<add> * 'Plugin' => array('/path/to/plugins', '/next/path/to/plugins'),
<ide> * ));
<ide> *
<ide> */ | 2 |
Python | Python | add tests class to the seupt.py script | 611cb841fa332c76479347a53ddd28e1b8d3dac5 | <ide><path>setup.py
<ide> import glob
<ide> import sys
<ide>
<del>from setuptools import setup
<del>
<add>from setuptools import setup, Command
<ide>
<ide> if sys.version_info < (2, 6) or (3, 0) <= sys.version_info < (3, 3):
<ide> print('Glances requires at least Python 2.6 or 3.3 to run.')
<ide> sys.exit(1)
<ide>
<add>class tests(Command):
<add> user_options = []
<add>
<add> def initialize_options(self):
<add> pass
<add>
<add> def finalize_options(self):
<add> pass
<add>
<add> def run(self):
<add> import subprocess
<add> import sys
<add> for t in glob.glob('unitest*.py'):
<add> ret = subprocess.call([sys.executable, t]) != 0
<add> if ret != 0:
<add> raise SystemExit(ret)
<add> raise SystemExit(0)
<ide>
<ide> def get_data_files():
<ide> data_files = [
<ide> def get_data_files():
<ide>
<ide> return data_files
<ide>
<del>
<ide> def get_requires():
<ide> requires = ['psutil>=2.0.0']
<ide> if sys.platform.startswith('win'):
<ide> def get_requires():
<ide> packages=['glances'],
<ide> include_package_data=True,
<ide> data_files=get_data_files(),
<add> cmdclass={'test': tests},
<ide> test_suite="unitest.py",
<ide> entry_points={"console_scripts": ["glances=glances:main"]},
<ide> classifiers=[ | 1 |
Go | Go | fix the attach behavior with -i | 537149829accde869430924cf988f64cfbd16f99 | <ide><path>container.go
<ide> func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, s
<ide> utils.Debugf("[start] attach stdout\n")
<ide> defer utils.Debugf("[end] attach stdout\n")
<ide> // If we are in StdinOnce mode, then close stdin
<del> if container.Config.StdinOnce {
<del> if stdin != nil {
<del> defer stdin.Close()
<del> }
<del> if stdinCloser != nil {
<del> defer stdinCloser.Close()
<del> }
<add> if container.Config.StdinOnce && stdin != nil {
<add> defer stdin.Close()
<add> }
<add> if stdinCloser != nil {
<add> defer stdinCloser.Close()
<ide> }
<ide> _, err := io.Copy(stdout, cStdout)
<ide> if err != nil {
<ide> func (container *Container) Attach(stdin io.ReadCloser, stdinCloser io.Closer, s
<ide> utils.Debugf("[start] attach stderr\n")
<ide> defer utils.Debugf("[end] attach stderr\n")
<ide> // If we are in StdinOnce mode, then close stdin
<del> if container.Config.StdinOnce {
<del> if stdin != nil {
<del> defer stdin.Close()
<del> }
<del> if stdinCloser != nil {
<del> defer stdinCloser.Close()
<del> }
<add> if container.Config.StdinOnce && stdin != nil {
<add> defer stdin.Close()
<add> }
<add> if stdinCloser != nil {
<add> defer stdinCloser.Close()
<ide> }
<ide> _, err := io.Copy(stderr, cStderr)
<ide> if err != nil { | 1 |
PHP | PHP | use actual value in selected/disabled check | b90cf78401880c5868b569b623dc8ba65dda7091 | <ide><path>src/View/Widget/SelectBoxWidget.php
<ide> protected function _renderOptions($options, $disabled, $selected, $escape)
<ide> ];
<ide> if (is_array($val) && isset($optAttrs['text'], $optAttrs['value'])) {
<ide> $optAttrs = $val;
<add> $key = $optAttrs['value'];
<ide> }
<ide> if ($this->_isSelected($key, $selected)) {
<ide> $optAttrs['selected'] = true;
<ide><path>tests/TestCase/View/Widget/SelectBoxWidgetTest.php
<ide> public function testRenderSelected()
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<add> /**
<add> * test complex option rendering with a selected value
<add> *
<add> * @return void
<add> */
<add> public function testRenderComplexSelected()
<add> {
<add> $select = new SelectBoxWidget($this->templates);
<add> $data = [
<add> 'id' => 'BirdName',
<add> 'name' => 'Birds[name]',
<add> 'val' => 'a',
<add> 'options' => [
<add> ['value' => 'a', 'text' => 'Albatross'],
<add> ['value' => 'b', 'text' => 'Budgie', 'data-foo' => 'bar'],
<add> ]
<add> ];
<add> $result = $select->render($data, $this->context);
<add> $expected = [
<add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'],
<add> ['option' => ['value' => 'a', 'selected' => 'selected']],
<add> 'Albatross',
<add> '/option',
<add> ['option' => ['value' => 'b', 'data-foo' => 'bar']],
<add> 'Budgie',
<add> '/option',
<add> '/select'
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<ide> /**
<ide> * test rendering a multi select
<ide> *
<ide> public function testRenderDisabledMultiple()
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<add> /**
<add> * test complex option rendering with a disabled element
<add> *
<add> * @return void
<add> */
<add> public function testRenderComplexDisabled()
<add> {
<add> $select = new SelectBoxWidget($this->templates);
<add> $data = [
<add> 'disabled' => ['b'],
<add> 'id' => 'BirdName',
<add> 'name' => 'Birds[name]',
<add> 'options' => [
<add> ['value' => 'a', 'text' => 'Albatross'],
<add> ['value' => 'b', 'text' => 'Budgie', 'data-foo' => 'bar'],
<add> ]
<add> ];
<add> $result = $select->render($data, $this->context);
<add> $expected = [
<add> 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'],
<add> ['option' => ['value' => 'a']],
<add> 'Albatross',
<add> '/option',
<add> ['option' => ['value' => 'b', 'data-foo' => 'bar', 'disabled' => 'disabled']],
<add> 'Budgie',
<add> '/option',
<add> '/select'
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<ide> /**
<ide> * test rendering with an empty value
<ide> * | 2 |
PHP | PHP | add the possibility to set an option shortcut | 55887ac32840fbd88cf7ed7040c126d0742aed89 | <ide><path>src/Illuminate/Console/Parser.php
<ide> protected static function parseOption($token)
<ide> $description = trim($description);
<ide> }
<ide>
<add> $shortcut = null;
<add> $matches = preg_split('/\s*\|\s*/', $token, 2);
<add> if (isset($matches[1])) {
<add> $shortcut = $matches[0];
<add> $token = $matches[1];
<add> }
<add>
<ide> switch (true) {
<ide> case Str::endsWith($token, '='):
<del> return new InputOption(trim($token, '='), null, InputOption::VALUE_OPTIONAL, $description);
<add> return new InputOption(trim($token, '='), $shortcut, InputOption::VALUE_OPTIONAL, $description);
<ide>
<ide> case Str::endsWith($token, '=*'):
<del> return new InputOption(trim($token, '=*'), null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description);
<add> return new InputOption(trim($token, '=*'), $shortcut, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description);
<ide>
<ide> case (preg_match('/(.+)\=(.+)/', $token, $matches)):
<del> return new InputOption($matches[1], null, InputOption::VALUE_OPTIONAL, $description, $matches[2]);
<add> return new InputOption($matches[1], $shortcut, InputOption::VALUE_OPTIONAL, $description, $matches[2]);
<ide>
<ide> default:
<del> return new InputOption($token, null, InputOption::VALUE_NONE, $description);
<add> return new InputOption($token, $shortcut, InputOption::VALUE_NONE, $description);
<ide> }
<ide> }
<ide> }
<ide><path>tests/Console/ConsoleParserTest.php
<ide> public function testBasicParameterParsing()
<ide> $this->assertTrue($results[2][0]->acceptValue());
<ide> $this->assertTrue($results[2][0]->isArray());
<ide> }
<add>
<add> public function testShortcutNameParsing()
<add> {
<add> $results = Parser::parse('command:name {--o|option}');
<add>
<add> $this->assertEquals('o', $results[2][0]->getShortcut());
<add> $this->assertEquals('option', $results[2][0]->getName());
<add> $this->assertFalse($results[2][0]->acceptValue());
<add>
<add> $results = Parser::parse('command:name {--o|option=}');
<add>
<add> $this->assertEquals('o', $results[2][0]->getShortcut());
<add> $this->assertEquals('option', $results[2][0]->getName());
<add> $this->assertTrue($results[2][0]->acceptValue());
<add>
<add> $results = Parser::parse('command:name {--o|option=*}');
<add>
<add> $this->assertEquals('command:name', $results[0]);
<add> $this->assertEquals('o', $results[2][0]->getShortcut());
<add> $this->assertEquals('option', $results[2][0]->getName());
<add> $this->assertTrue($results[2][0]->acceptValue());
<add> $this->assertTrue($results[2][0]->isArray());
<add>
<add> $results = Parser::parse('command:name {--o|option=* : The option description.}');
<add>
<add> $this->assertEquals('command:name', $results[0]);
<add> $this->assertEquals('o', $results[2][0]->getShortcut());
<add> $this->assertEquals('option', $results[2][0]->getName());
<add> $this->assertEquals('The option description.', $results[2][0]->getDescription());
<add> $this->assertTrue($results[2][0]->acceptValue());
<add> $this->assertTrue($results[2][0]->isArray());
<add>
<add> $results = Parser::parse('command:name
<add> {--o|option=* : The option description.}');
<add>
<add> $this->assertEquals('command:name', $results[0]);
<add> $this->assertEquals('o', $results[2][0]->getShortcut());
<add> $this->assertEquals('option', $results[2][0]->getName());
<add> $this->assertEquals('The option description.', $results[2][0]->getDescription());
<add> $this->assertTrue($results[2][0]->acceptValue());
<add> $this->assertTrue($results[2][0]->isArray());
<add> }
<ide> } | 2 |
PHP | PHP | fix cs error | 97852552d5d6fe6c73aac0649c8474367d82eef1 | <ide><path>tests/TestCase/Mailer/EmailTest.php
<ide> public function testFormatAddress()
<ide>
<ide> $result = $this->Email->getMessage()->formatAddress([
<ide> 'cake@cakephp.org' => 'cake@cakephp.org',
<del> 'php@cakephp.org' => 'php@cakephp.org'
<add> 'php@cakephp.org' => 'php@cakephp.org',
<ide> ]);
<ide> $expected = ['cake@cakephp.org', 'php@cakephp.org'];
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $result = $this->Email->getMessage()->formatAddress([
<ide> 'cake@cakephp.org' => 'CakePHP',
<del> 'php@cakephp.org' => 'Cake'
<add> 'php@cakephp.org' => 'Cake',
<ide> ]);
<ide> $expected = ['CakePHP <cake@cakephp.org>', 'Cake <php@cakephp.org>'];
<ide> $this->assertSame($expected, $result); | 1 |
Java | Java | update license header for recently modified files | 0829cbfdd3adc4459e47b6c4e1411dba796f964a | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 10 |
PHP | PHP | deliver() config argument | 75397c58dd7b0cfcb86dd0c41c9757338ee02335 | <ide><path>src/Mailer/Email.php
<ide> class Email implements JsonSerializable, Serializable
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param array|string|null $config Array of configs, or string to load configs from email.php
<add> * @param array|string|null $config Array of configs, or string to load configs from app.php
<ide> */
<ide> public function __construct($config = null)
<ide> {
<ide> protected function flatten($value)
<ide> * @param string|array|null $to Address to send (see Cake\Mailer\Email::to()). If null, will try to use 'to' from transport config
<ide> * @param string|null $subject String of subject or null to use 'subject' from transport config
<ide> * @param string|array|null $message String with message or array with variables to be used in render
<del> * @param string|array $transportConfig String to use config from EmailConfig or array with configs
<add> * @param string|array $config String to use Email delivery profile from app.php or array with configs
<ide> * @param bool $send Send the email or just return the instance pre-configured
<ide> * @return static Instance of Cake\Mailer\Email
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'default', $send = true)
<add> public static function deliver($to = null, $subject = null, $message = null, $config = 'default', $send = true)
<ide> {
<ide> $class = __CLASS__;
<ide>
<del> if (is_array($transportConfig) && !isset($transportConfig['transport'])) {
<del> $transportConfig['transport'] = 'default';
<add> if (is_array($config) && !isset($config['transport'])) {
<add> $config['transport'] = 'default';
<ide> }
<ide> /* @var \Cake\Mailer\Email $instance */
<del> $instance = new $class($transportConfig);
<add> $instance = new $class($config);
<ide> if ($to !== null) {
<ide> $instance->setTo($to);
<ide> } | 1 |
PHP | PHP | fix prefix paths for controller bake | 92c89f782dc5fb9f2b04ea1eb7ba96a3c44a6c65 | <ide><path>src/Console/Command/Task/ControllerTask.php
<ide> public function bakeController($controllerName, $data) {
<ide> return $contents;
<ide> }
<ide>
<add>/**
<add> * Gets the path for output. Checks the plugin property
<add> * and returns the correct path.
<add> *
<add> * @return string Path to output.
<add> */
<add> public function getPath() {
<add> $path = parent::getPath();
<add> if (!empty($this->params['prefix'])) {
<add> $path .= Inflector::camelize($this->params['prefix']) . DS;
<add> }
<add> return $path;
<add> }
<add>
<ide> /**
<ide> * Assembles and writes a unit test file
<ide> *
<ide><path>tests/TestCase/Console/Command/Task/ControllerTaskTest.php
<ide> public function setUp() {
<ide> );
<ide> $this->Task->name = 'Controller';
<ide> $this->Task->connection = 'test';
<add> $this->Task->path = '/my/path/';
<ide>
<ide> $this->Task->Template = new TemplateTask($out, $out, $in);
<ide> $this->Task->Template->params['theme'] = 'default';
<ide> public function testBakeActions() {
<ide> $this->Task->params['helpers'] = 'Html,Time';
<ide> $this->Task->params['components'] = 'Csrf, Auth';
<ide>
<add> $filename = '/my/path/BakeArticlesController.php';
<add> $this->Task->expects($this->at(1))
<add> ->method('createFile')
<add> ->with(
<add> $filename,
<add> $this->stringContains('class BakeArticlesController')
<add> );
<ide> $result = $this->Task->bake('BakeArticles');
<add>
<ide> $this->assertTextContains('public function add(', $result);
<ide> $this->assertTextContains('public function index(', $result);
<ide> $this->assertTextContains('public function view(', $result);
<ide> public function testBakeActions() {
<ide> public function testBakePrefixed() {
<ide> $this->Task->params['prefix'] = 'Admin';
<ide>
<add> $filename = '/my/path/Admin/BakeArticlesController.php';
<add> $this->Task->expects($this->at(1))
<add> ->method('createFile')
<add> ->with($filename, $this->anything());
<ide> $result = $this->Task->bake('BakeArticles');
<add>
<ide> $this->assertTextContains('namespace App\Controller\Admin;', $result);
<ide> $this->assertTextContains('use App\Controller\AppController;', $result);
<ide> } | 2 |
Ruby | Ruby | define a synchronousqueue for test in action pack | d0c25f253f43acba6ce27a1d3116c16fa4d3b536 | <ide><path>actionpack/test/abstract_unit.rb
<ide> require 'active_record'
<ide> require 'action_controller/caching'
<ide> require 'action_controller/caching/sweeping'
<del>require 'rails/queueing'
<ide>
<ide> require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
<ide>
<ide> class << self
<ide> def env
<ide> @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "test")
<ide> end
<del>
<del> def queue
<del> @queue ||= Rails::Queueing::Container.new(Rails::Queueing::SynchronousQueue.new)
<del> end
<del>
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/controller/assert_select_test.rb
<ide> require 'action_mailer'
<ide> ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH
<ide>
<add>class SynchronousQueue < Queue
<add> def push(job)
<add> job.run
<add> end
<add> alias << push
<add> alias enq push
<add>end
<add>
<add>ActionMailer::Base.queue = SynchronousQueue.new
<add>
<ide> class AssertSelectTest < ActionController::TestCase
<ide> Assertion = ActiveSupport::TestCase::Assertion
<ide> | 2 |
Ruby | Ruby | remove flaky test." | cc0ea9aec3b5d556082ca1e24910fe11cc2ef338 | <ide><path>Library/Homebrew/test/cask/cmd/upgrade_spec.rb
<ide> expect(local_transmission.versions).to include("2.60")
<ide> expect(local_transmission.versions).not_to include("2.61")
<ide> end
<add>
<add> it 'would update "auto_updates" and "latest" Casks when their tokens are provided in the command line' do
<add> local_caffeine = Cask::CaskLoader.load("local-caffeine")
<add> local_caffeine_path = Cask::Config.global.appdir.join("Caffeine.app")
<add> auto_updates = Cask::CaskLoader.load("auto-updates")
<add> auto_updates_path = Cask::Config.global.appdir.join("MyFancyApp.app")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<add>
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.57")
<add>
<add> described_class.run("--dry-run", "local-caffeine", "auto-updates")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<add> expect(local_caffeine.versions).not_to include("1.2.3")
<add>
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.57")
<add> expect(auto_updates.versions).not_to include("2.61")
<add> end
<ide> end
<ide>
<ide> describe "with --greedy it checks additional Casks" do | 1 |
PHP | PHP | fix failing tests caused by previous commit | 6d6ac1083425ecc4e0efe4be6ce98d8cea6a2989 | <ide><path>lib/Cake/Console/Command/Task/FixtureTask.php
<ide> public function getPath() {
<ide> */
<ide> protected function _generateSchema($tableInfo) {
<ide> $schema = $this->_Schema->generateTable('f', $tableInfo);
<del> return substr($schema, 10, -2);
<add> return substr($schema, 13, -2);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Console/Command/SchemaShellTest.php
<ide> public function testGenerateWithPlugins() {
<ide> $contents = $this->file->read();
<ide>
<ide> $this->assertRegExp('/class TestPluginSchema/', $contents);
<del> $this->assertRegExp('/var \$posts/', $contents);
<del> $this->assertRegExp('/var \$auth_users/', $contents);
<del> $this->assertRegExp('/var \$authors/', $contents);
<del> $this->assertRegExp('/var \$test_plugin_comments/', $contents);
<del> $this->assertNotRegExp('/var \$users/', $contents);
<del> $this->assertNotRegExp('/var \$articles/', $contents);
<add> $this->assertRegExp('/public \$posts/', $contents);
<add> $this->assertRegExp('/public \$auth_users/', $contents);
<add> $this->assertRegExp('/public \$authors/', $contents);
<add> $this->assertRegExp('/public \$test_plugin_comments/', $contents);
<add> $this->assertNotRegExp('/public \$users/', $contents);
<add> $this->assertNotRegExp('/public \$articles/', $contents);
<ide> CakePlugin::unload();
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Console/Command/Task/FixtureTaskTest.php
<ide> App::uses('Shell', 'Console');
<ide> App::uses('ConsoleOutput', 'Console');
<ide> App::uses('ConsoleInput', 'Console');
<add>App::uses('ModelTask', 'Console/Command/Task');
<ide> App::uses('FixtureTask', 'Console/Command/Task');
<ide> App::uses('TemplateTask', 'Console/Command/Task');
<ide> App::uses('DbConfigTask', 'Console/Command/Task');
<ide><path>lib/Cake/Test/Case/Model/CakeSchemaTest.php
<ide> public function testGenerateTable() {
<ide> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
<ide> );
<ide> $result = $this->Schema->generateTable('posts', $posts);
<del> $this->assertRegExp('/var \$posts/', $result);
<add> $this->assertRegExp('/public \$posts/', $result);
<ide> }
<ide> /**
<ide> * testSchemaWrite method | 4 |
Javascript | Javascript | add tests for options.fs in fs streams | 39ff64756bd5bc7147236b36ee9444ceddb3e6d2 | <ide><path>test/parallel/test-fs-stream-fs-options.js
<add>'use strict';
<add>
<add>require('../common');
<add>const fixtures = require('../common/fixtures');
<add>const path = require('path');
<add>const fs = require('fs');
<add>const assert = require('assert');
<add>
<add>const tmpdir = require('../common/tmpdir');
<add>tmpdir.refresh();
<add>
<add>const streamOpts = ['open', 'close'];
<add>const writeStreamOptions = [...streamOpts, 'write'];
<add>const readStreamOptions = [...streamOpts, 'read'];
<add>const originalFs = { fs };
<add>
<add>{
<add> const file = path.join(tmpdir.path, 'write-end-test0.txt');
<add>
<add> writeStreamOptions.forEach((fn) => {
<add> const overrideFs = Object.assign({}, originalFs.fs, { [fn]: null });
<add> if (fn === 'write') overrideFs.writev = null;
<add>
<add> const opts = {
<add> fs: overrideFs
<add> };
<add> assert.throws(
<add> () => fs.createWriteStream(file, opts), {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: `The "options.fs.${fn}" property must be of type function. ` +
<add> 'Received null'
<add> },
<add> `createWriteStream options.fs.${fn} should throw if isn't a function`
<add> );
<add> });
<add>}
<add>
<add>{
<add> const file = path.join(tmpdir.path, 'write-end-test0.txt');
<add> const overrideFs = Object.assign({}, originalFs.fs, { writev: 'not a fn' });
<add> const opts = {
<add> fs: overrideFs
<add> };
<add> assert.throws(
<add> () => fs.createWriteStream(file, opts), {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: 'The "options.fs.writev" property must be of type function. ' +
<add> 'Received type string (\'not a fn\')'
<add> },
<add> 'createWriteStream options.fs.writev should throw if isn\'t a function'
<add> );
<add>}
<add>
<add>{
<add> const file = fixtures.path('x.txt');
<add> readStreamOptions.forEach((fn) => {
<add> const overrideFs = Object.assign({}, originalFs.fs, { [fn]: null });
<add> const opts = {
<add> fs: overrideFs
<add> };
<add> assert.throws(
<add> () => fs.createReadStream(file, opts), {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError',
<add> message: `The "options.fs.${fn}" property must be of type function. ` +
<add> 'Received null'
<add> },
<add> `createReadStream options.fs.${fn} should throw if isn't a function`
<add> );
<add> });
<add>} | 1 |
Javascript | Javascript | turn reactdomfibercomponent into a singleton | ec178acf151f2642897f3ef5aa29005e059be4b8 | <ide><path>src/renderers/dom/fiber/ReactDOMFiberComponent.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactDOMFiberComponent
<add> * @flow
<ide> */
<ide>
<ide> /* global hasOwnProperty:true */
<ide> var EventPluginRegistry = require('EventPluginRegistry');
<ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
<ide> var ReactDOMComponentFlags = require('ReactDOMComponentFlags');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<del>var ReactDOMInput = require('ReactDOMInput');
<del>var ReactDOMOption = require('ReactDOMOption');
<del>var ReactDOMSelect = require('ReactDOMSelect');
<del>var ReactDOMTextarea = require('ReactDOMTextarea');
<add>var ReactDOMFiberInput = require('ReactDOMFiberInput');
<add>var ReactDOMFiberOption = require('ReactDOMFiberOption');
<add>var ReactDOMFiberSelect = require('ReactDOMFiberSelect');
<add>var ReactDOMFiberTextarea = require('ReactDOMFiberTextarea');
<ide> var ReactInstrumentation = require('ReactInstrumentation');
<ide> var ReactMultiChild = require('ReactMultiChild');
<ide> var ReactServerRenderingTransaction = require('ReactServerRenderingTransaction');
<ide> function putListener() {
<ide>
<ide> function inputPostMount() {
<ide> var inst = this;
<del> ReactDOMInput.postMountWrapper(inst);
<add> ReactDOMFiberInput.postMountWrapper(inst);
<ide> }
<ide>
<ide> function textareaPostMount() {
<ide> var inst = this;
<del> ReactDOMTextarea.postMountWrapper(inst);
<add> ReactDOMFiberTextarea.postMountWrapper(inst);
<ide> }
<ide>
<ide> function optionPostMount() {
<ide> var inst = this;
<del> ReactDOMOption.postMountWrapper(inst);
<add> ReactDOMFiberOption.postMountWrapper(inst);
<ide> }
<ide>
<ide> var setAndValidateContentChildDev = emptyFunction;
<ide> function trapBubbledEventsLocal() {
<ide> }
<ide>
<ide> function postUpdateSelectWrapper() {
<del> ReactDOMSelect.postUpdateWrapper(this);
<add> ReactDOMFiberSelect.postUpdateWrapper(this);
<ide> }
<ide>
<ide> // For HTML, certain tags should omit their close tag. We keep a whitelist for
<ide> function isCustomComponent(tagName, props) {
<ide> return tagName.indexOf('-') >= 0 || props.is != null;
<ide> }
<ide>
<del>var globalIdCounter = 1;
<ide>
<ide> /**
<del> * Creates a new React class that is idempotent and capable of containing other
<del> * React components. It accepts event listeners and DOM properties that are
<del> * valid according to `DOMProperty`.
<add> * Creates markup for the open tag and all attributes.
<ide> *
<del> * - Event listeners: `onClick`, `onMouseDown`, etc.
<del> * - DOM properties: `className`, `name`, `title`, etc.
<add> * This method has side effects because events get registered.
<ide> *
<del> * The `style` property functions differently from the DOM API. It accepts an
<del> * object mapping of style properties to values.
<add> * Iterating over object properties is faster than iterating over arrays.
<add> * @see http://jsperf.com/obj-vs-arr-iteration
<ide> *
<del> * @constructor ReactDOMComponent
<del> * @extends ReactMultiChild
<add> * @private
<add> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<add> * @param {object} props
<add> * @return {string} Markup of opening tag.
<ide> */
<del>function ReactDOMComponent(element) {
<del> var tag = element.type;
<del> validateDangerousTag(tag);
<del> this._currentElement = element;
<del> this._tag = tag.toLowerCase();
<del> this._namespaceURI = null;
<del> this._renderedChildren = null;
<del> this._previousStyle = null;
<del> this._previousStyleCopy = null;
<del> this._hostNode = null;
<del> this._hostParent = null;
<del> this._rootNodeID = 0;
<del> this._domID = 0;
<del> this._hostContainerInfo = null;
<del> this._wrapperState = null;
<del> this._topLevelWrapper = null;
<del> this._flags = 0;
<del> if (__DEV__) {
<del> this._ancestorInfo = null;
<del> setAndValidateContentChildDev.call(this, null);
<add>function createOpenTagMarkupAndPutListeners(workInProgress, transaction, props) {
<add> var ret = '<' + workInProgress._currentElement.type;
<add>
<add> for (var propKey in props) {
<add> if (!props.hasOwnProperty(propKey)) {
<add> continue;
<add> }
<add> var propValue = props[propKey];
<add> if (propValue == null) {
<add> continue;
<add> }
<add> if (registrationNameModules.hasOwnProperty(propKey)) {
<add> if (propValue) {
<add> enqueuePutListener(workInProgress, propKey, propValue, transaction);
<add> }
<add> } else {
<add> if (propKey === STYLE) {
<add> if (propValue) {
<add> if (__DEV__) {
<add> // See `_updateDOMProperties`. style block
<add> workInProgress._previousStyle = propValue;
<add> }
<add> propValue = workInProgress._previousStyleCopy = Object.assign({}, props.style);
<add> }
<add> propValue = CSSPropertyOperations.createMarkupForStyles(propValue, workInProgress);
<add> }
<add> var markup = null;
<add> if (workInProgress._tag != null && isCustomComponent(workInProgress._tag, props)) {
<add> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<add> markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
<add> }
<add> } else {
<add> markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
<add> }
<add> if (markup) {
<add> ret += ' ' + markup;
<add> }
<add> }
<add> }
<add>
<add> // For static pages, no need to put React ID and checksum. Saves lots of
<add> // bytes.
<add> if (transaction.renderToStaticMarkup) {
<add> return ret;
<add> }
<add>
<add> if (!workInProgress._hostParent) {
<add> ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
<add> }
<add> ret += ' ' + DOMPropertyOperations.createMarkupForID(workInProgress._domID);
<add> return ret;
<add>}
<add>
<add>/**
<add> * Creates markup for the content between the tags.
<add> *
<add> * @private
<add> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<add> * @param {object} props
<add> * @param {object} context
<add> * @return {string} Content markup.
<add> */
<add>function createContentMarkup(workInProgress, transaction, props, context) {
<add> var ret = '';
<add>
<add> // Intentional use of != to avoid catching zero/false.
<add> var innerHTML = props.dangerouslySetInnerHTML;
<add> if (innerHTML != null) {
<add> if (innerHTML.__html != null) {
<add> ret = innerHTML.__html;
<add> }
<add> } else {
<add> var contentToUse =
<add> CONTENT_TYPES[typeof props.children] ? props.children : null;
<add> var childrenToUse = contentToUse != null ? null : props.children;
<add> if (contentToUse != null) {
<add> // TODO: Validate that text is allowed as a child of this node
<add> ret = escapeTextContentForBrowser(contentToUse);
<add> if (__DEV__) {
<add> setAndValidateContentChildDev.call(workInProgress, contentToUse);
<add> }
<add> } else if (childrenToUse != null) {
<add> var mountImages = workInProgress.mountChildren(
<add> childrenToUse,
<add> transaction,
<add> context
<add> );
<add> ret = mountImages.join('');
<add> }
<add> }
<add> if (newlineEatingTags[workInProgress._tag] && ret.charAt(0) === '\n') {
<add> // text/html ignores the first character in these tags if it's a newline
<add> // Prefer to break application/xml over text/html (for now) by adding
<add> // a newline specifically to get eaten by the parser. (Alternately for
<add> // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
<add> // \r is normalized out by HTMLTextAreaElement#value.)
<add> // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
<add> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
<add> // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
<add> // See: Parsing of "textarea" "listing" and "pre" elements
<add> // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
<add> return '\n' + ret;
<add> } else {
<add> return ret;
<add> }
<add>}
<add>
<add>function createInitialChildren(workInProgress, transaction, props, context, lazyTree) {
<add> // Intentional use of != to avoid catching zero/false.
<add> var innerHTML = props.dangerouslySetInnerHTML;
<add> if (innerHTML != null) {
<add> if (innerHTML.__html != null) {
<add> DOMLazyTree.queueHTML(lazyTree, innerHTML.__html);
<add> }
<add> } else {
<add> var contentToUse =
<add> CONTENT_TYPES[typeof props.children] ? props.children : null;
<add> var childrenToUse = contentToUse != null ? null : props.children;
<add> // TODO: Validate that text is allowed as a child of this node
<add> if (contentToUse != null) {
<add> // Avoid setting textContent when the text is empty. In IE11 setting
<add> // textContent on a text area will cause the placeholder to not
<add> // show within the textarea until it has been focused and blurred again.
<add> // https://github.com/facebook/react/issues/6731#issuecomment-254874553
<add> if (contentToUse !== '') {
<add> if (__DEV__) {
<add> setAndValidateContentChildDev.call(workInProgress, contentToUse);
<add> }
<add> DOMLazyTree.queueText(lazyTree, contentToUse);
<add> }
<add> } else if (childrenToUse != null) {
<add> var mountImages = workInProgress.mountChildren(
<add> childrenToUse,
<add> transaction,
<add> context
<add> );
<add> for (var i = 0; i < mountImages.length; i++) {
<add> DOMLazyTree.queueChild(lazyTree, mountImages[i]);
<add> }
<add> }
<add> }
<add>}
<add>
<add>/**
<add> * Reconciles the properties by detecting differences in property values and
<add> * updating the DOM as necessary. This function is probably the single most
<add> * critical path for performance optimization.
<add> *
<add> * TODO: Benchmark whether checking for changed values in memory actually
<add> * improves performance (especially statically positioned elements).
<add> * TODO: Benchmark the effects of putting workInProgress at the top since 99% of props
<add> * do not change for a given reconciliation.
<add> * TODO: Benchmark areas that can be improved with caching.
<add> *
<add> * @private
<add> * @param {object} lastProps
<add> * @param {object} nextProps
<add> * @param {?DOMElement} node
<add> */
<add>function updateDOMProperties(
<add> workInProgress,
<add> lastProps,
<add> nextProps,
<add> transaction,
<add> isCustomComponentTag
<add>) {
<add> var propKey;
<add> var styleName;
<add> var styleUpdates;
<add> for (propKey in lastProps) {
<add> if (nextProps.hasOwnProperty(propKey) ||
<add> !lastProps.hasOwnProperty(propKey) ||
<add> lastProps[propKey] == null) {
<add> continue;
<add> }
<add> if (propKey === STYLE) {
<add> var lastStyle = workInProgress._previousStyleCopy;
<add> for (styleName in lastStyle) {
<add> if (lastStyle.hasOwnProperty(styleName)) {
<add> styleUpdates = styleUpdates || {};
<add> styleUpdates[styleName] = '';
<add> }
<add> }
<add> workInProgress._previousStyleCopy = null;
<add> } else if (registrationNameModules.hasOwnProperty(propKey)) {
<add> if (lastProps[propKey]) {
<add> // Only call deleteListener if there was a listener previously or
<add> // else willDeleteListener gets called when there wasn't actually a
<add> // listener (e.g., onClick={null})
<add> deleteListener(workInProgress, propKey);
<add> }
<add> } else if (isCustomComponent(workInProgress._tag, lastProps)) {
<add> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<add> DOMPropertyOperations.deleteValueForAttribute(
<add> getNode(workInProgress),
<add> propKey
<add> );
<add> }
<add> } else if (
<add> DOMProperty.properties[propKey] ||
<add> DOMProperty.isCustomAttribute(propKey)) {
<add> DOMPropertyOperations.deleteValueForProperty(getNode(workInProgress), propKey);
<add> }
<add> }
<add> for (propKey in nextProps) {
<add> var nextProp = nextProps[propKey];
<add> var lastProp =
<add> propKey === STYLE ? workInProgress._previousStyleCopy :
<add> lastProps != null ? lastProps[propKey] : undefined;
<add> if (!nextProps.hasOwnProperty(propKey) ||
<add> nextProp === lastProp ||
<add> nextProp == null && lastProp == null) {
<add> continue;
<add> }
<add> if (propKey === STYLE) {
<add> if (nextProp) {
<add> if (__DEV__) {
<add> checkAndWarnForMutatedStyle(
<add> workInProgress._previousStyleCopy,
<add> workInProgress._previousStyle,
<add> workInProgress
<add> );
<add> workInProgress._previousStyle = nextProp;
<add> }
<add> nextProp = workInProgress._previousStyleCopy = Object.assign({}, nextProp);
<add> } else {
<add> workInProgress._previousStyleCopy = null;
<add> }
<add> if (lastProp) {
<add> // Unset styles on `lastProp` but not on `nextProp`.
<add> for (styleName in lastProp) {
<add> if (lastProp.hasOwnProperty(styleName) &&
<add> (!nextProp || !nextProp.hasOwnProperty(styleName))) {
<add> styleUpdates = styleUpdates || {};
<add> styleUpdates[styleName] = '';
<add> }
<add> }
<add> // Update styles that changed since `lastProp`.
<add> for (styleName in nextProp) {
<add> if (nextProp.hasOwnProperty(styleName) &&
<add> lastProp[styleName] !== nextProp[styleName]) {
<add> styleUpdates = styleUpdates || {};
<add> styleUpdates[styleName] = nextProp[styleName];
<add> }
<add> }
<add> } else {
<add> // Relies on `updateStylesByID` not mutating `styleUpdates`.
<add> styleUpdates = nextProp;
<add> }
<add> } else if (registrationNameModules.hasOwnProperty(propKey)) {
<add> if (nextProp) {
<add> enqueuePutListener(workInProgress, propKey, nextProp, transaction);
<add> } else if (lastProp) {
<add> deleteListener(workInProgress, propKey);
<add> }
<add> } else if (isCustomComponentTag) {
<add> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<add> DOMPropertyOperations.setValueForAttribute(
<add> getNode(workInProgress),
<add> propKey,
<add> nextProp
<add> );
<add> }
<add> } else if (
<add> DOMProperty.properties[propKey] ||
<add> DOMProperty.isCustomAttribute(propKey)) {
<add> var node = getNode(workInProgress);
<add> // If we're updating to null or undefined, we should remove the property
<add> // from the DOM node instead of inadvertently setting to a string. This
<add> // brings us in line with the same behavior we have on initial render.
<add> if (nextProp != null) {
<add> DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
<add> } else {
<add> DOMPropertyOperations.deleteValueForProperty(node, propKey);
<add> }
<add> }
<add> }
<add> if (styleUpdates) {
<add> CSSPropertyOperations.setValueForStyles(
<add> getNode(workInProgress),
<add> styleUpdates,
<add> workInProgress
<add> );
<add> }
<add>}
<add>
<add>/**
<add> * Reconciles the children with the various properties that affect the
<add> * children content.
<add> *
<add> * @param {object} lastProps
<add> * @param {object} nextProps
<add> * @param {ReactReconcileTransaction} transaction
<add> * @param {object} context
<add> */
<add>function updateDOMChildren(workInProgress, lastProps, nextProps, transaction, context) {
<add> var lastContent =
<add> CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
<add> var nextContent =
<add> CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
<add>
<add> var lastHtml =
<add> lastProps.dangerouslySetInnerHTML &&
<add> lastProps.dangerouslySetInnerHTML.__html;
<add> var nextHtml =
<add> nextProps.dangerouslySetInnerHTML &&
<add> nextProps.dangerouslySetInnerHTML.__html;
<add>
<add> // Note the use of `!=` which checks for null or undefined.
<add> var lastChildren = lastContent != null ? null : lastProps.children;
<add> var nextChildren = nextContent != null ? null : nextProps.children;
<add>
<add> // If we're switching from children to content/html or vice versa, remove
<add> // the old content
<add> var lastHasContentOrHtml = lastContent != null || lastHtml != null;
<add> var nextHasContentOrHtml = nextContent != null || nextHtml != null;
<add> if (lastChildren != null && nextChildren == null) {
<add> workInProgress.updateChildren(null, transaction, context);
<add> } else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
<add> workInProgress.updateTextContent('');
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onSetChildren(workInProgress._debugID, []);
<add> }
<add> }
<add>
<add> if (nextContent != null) {
<add> if (lastContent !== nextContent) {
<add> workInProgress.updateTextContent('' + nextContent);
<add> if (__DEV__) {
<add> setAndValidateContentChildDev.call(workInProgress, nextContent);
<add> }
<add> }
<add> } else if (nextHtml != null) {
<add> if (lastHtml !== nextHtml) {
<add> workInProgress.updateMarkup('' + nextHtml);
<add> }
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onSetChildren(workInProgress._debugID, []);
<add> }
<add> } else if (nextChildren != null) {
<add> if (__DEV__) {
<add> setAndValidateContentChildDev.call(workInProgress, null);
<add> }
<add>
<add> workInProgress.updateChildren(nextChildren, transaction, context);
<ide> }
<ide> }
<ide>
<del>ReactDOMComponent.displayName = 'ReactDOMComponent';
<add>var globalIdCounter = 1;
<add>
<add>var ReactDOMFiberComponent = {
<ide>
<del>ReactDOMComponent.Mixin = {
<ide>
<ide> /**
<ide> * Generates root tag markup then recurses. This method has side effects and
<ide> ReactDOMComponent.Mixin = {
<ide> * @return {string} The computed markup.
<ide> */
<ide> mountComponent: function(
<add> workInProgress : Fiber,
<ide> transaction,
<ide> hostParent,
<ide> hostContainerInfo,
<ide> context
<ide> ) {
<del> this._rootNodeID = globalIdCounter++;
<del> this._domID = hostContainerInfo._idCounter++;
<del> this._hostParent = hostParent;
<del> this._hostContainerInfo = hostContainerInfo;
<add> // validateDangerousTag(tag);
<add> // workInProgress._tag = tag.toLowerCase();
<add> // setAndValidateContentChildDev.call(workInProgress, null);
<add>
<add> workInProgress._rootNodeID = globalIdCounter++;
<add> workInProgress._domID = hostContainerInfo._idCounter++;
<add> workInProgress._hostParent = hostParent;
<add> workInProgress._hostContainerInfo = hostContainerInfo;
<ide>
<del> var props = this._currentElement.props;
<add> var props = workInProgress._currentElement.props;
<ide>
<del> switch (this._tag) {
<add> switch (workInProgress._tag) {
<ide> case 'audio':
<ide> case 'form':
<ide> case 'iframe':
<ide> ReactDOMComponent.Mixin = {
<ide> case 'object':
<ide> case 'source':
<ide> case 'video':
<del> this._wrapperState = {
<add> workInProgress._wrapperState = {
<ide> listeners: null,
<ide> };
<del> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
<add> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, workInProgress);
<ide> break;
<ide> case 'input':
<del> ReactDOMInput.mountWrapper(this, props, hostParent);
<del> props = ReactDOMInput.getHostProps(this, props);
<del> transaction.getReactMountReady().enqueue(trackInputValue, this);
<del> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
<add> ReactDOMFiberInput.mountWrapper(workInProgress, props, hostParent);
<add> props = ReactDOMFiberInput.getHostProps(workInProgress, props);
<add> transaction.getReactMountReady().enqueue(trackInputValue, workInProgress);
<add> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, workInProgress);
<ide> // For controlled components we always need to ensure we're listening
<ide> // to onChange. Even if there is no listener.
<del> ensureListeningTo(this, 'onChange', transaction);
<add> ensureListeningTo(workInProgress, 'onChange', transaction);
<ide> break;
<ide> case 'option':
<del> ReactDOMOption.mountWrapper(this, props, hostParent);
<del> props = ReactDOMOption.getHostProps(this, props);
<add> ReactDOMFiberOption.mountWrapper(workInProgress, props, hostParent);
<add> props = ReactDOMFiberOption.getHostProps(workInProgress, props);
<ide> break;
<ide> case 'select':
<del> ReactDOMSelect.mountWrapper(this, props, hostParent);
<del> props = ReactDOMSelect.getHostProps(this, props);
<del> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
<add> ReactDOMFiberSelect.mountWrapper(workInProgress, props, hostParent);
<add> props = ReactDOMFiberSelect.getHostProps(workInProgress, props);
<add> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, workInProgress);
<ide> // For controlled components we always need to ensure we're listening
<ide> // to onChange. Even if there is no listener.
<del> ensureListeningTo(this, 'onChange', transaction);
<add> ensureListeningTo(workInProgress, 'onChange', transaction);
<ide> break;
<ide> case 'textarea':
<del> ReactDOMTextarea.mountWrapper(this, props, hostParent);
<del> props = ReactDOMTextarea.getHostProps(this, props);
<del> transaction.getReactMountReady().enqueue(trackInputValue, this);
<del> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
<add> ReactDOMFiberTextarea.mountWrapper(workInProgress, props, hostParent);
<add> props = ReactDOMFiberTextarea.getHostProps(workInProgress, props);
<add> transaction.getReactMountReady().enqueue(trackInputValue, workInProgress);
<add> transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, workInProgress);
<ide> // For controlled components we always need to ensure we're listening
<ide> // to onChange. Even if there is no listener.
<del> ensureListeningTo(this, 'onChange', transaction);
<add> ensureListeningTo(workInProgress, 'onChange', transaction);
<ide> break;
<ide> }
<ide>
<del> assertValidProps(this, props);
<add> assertValidProps(workInProgress, props);
<ide>
<ide> // We create tags in the namespace of their parent container, except HTML
<ide> // tags get no namespace.
<ide> ReactDOMComponent.Mixin = {
<ide> namespaceURI = DOMNamespaces.html;
<ide> }
<ide> if (namespaceURI === DOMNamespaces.html) {
<del> if (this._tag === 'svg') {
<add> if (workInProgress._tag === 'svg') {
<ide> namespaceURI = DOMNamespaces.svg;
<del> } else if (this._tag === 'math') {
<add> } else if (workInProgress._tag === 'math') {
<ide> namespaceURI = DOMNamespaces.mathml;
<ide> }
<ide> }
<del> this._namespaceURI = namespaceURI;
<add> workInProgress._namespaceURI = namespaceURI;
<ide>
<ide> if (__DEV__) {
<ide> var parentInfo;
<ide> ReactDOMComponent.Mixin = {
<ide> if (parentInfo) {
<ide> // parentInfo should always be present except for the top-level
<ide> // component when server rendering
<del> validateDOMNesting(this._tag, null, this, parentInfo);
<add> validateDOMNesting(workInProgress._tag, null, workInProgress, parentInfo);
<ide> }
<del> this._ancestorInfo =
<del> validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
<add> workInProgress._ancestorInfo =
<add> validateDOMNesting.updatedAncestorInfo(parentInfo, workInProgress._tag, workInProgress);
<ide> }
<ide>
<ide> var mountImage;
<del> var type = this._currentElement.type;
<add> var type = workInProgress._currentElement.type;
<ide> if (transaction.useCreateElement) {
<ide> var ownerDocument = hostContainerInfo._ownerDocument;
<ide> var el;
<ide> if (namespaceURI === DOMNamespaces.html) {
<del> if (this._tag === 'script') {
<add> if (workInProgress._tag === 'script') {
<ide> // Create the script via .innerHTML so its "parser-inserted" flag is
<ide> // set to true and it does not execute
<ide> var div = ownerDocument.createElement('div');
<ide> ReactDOMComponent.Mixin = {
<ide> type
<ide> );
<ide> }
<del> var isCustomComponentTag = isCustomComponent(this._tag, props);
<add> var isCustomComponentTag = isCustomComponent(workInProgress._tag, props);
<ide> if (__DEV__ && isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) {
<del> var owner = this._currentElement._owner;
<add> var owner = workInProgress._currentElement._owner;
<ide> var name = owner && owner.getName() || 'A component';
<ide> warning(
<ide> false,
<ide> ReactDOMComponent.Mixin = {
<ide> );
<ide> didWarnShadyDOM = true;
<ide> }
<del> ReactDOMComponentTree.precacheNode(this, el);
<del> this._flags |= Flags.hasCachedChildNodes;
<del> if (!this._hostParent) {
<add> ReactDOMComponentTree.precacheNode(workInProgress, el);
<add> workInProgress._flags |= Flags.hasCachedChildNodes;
<add> if (!workInProgress._hostParent) {
<ide> DOMPropertyOperations.setAttributeForRoot(el);
<ide> }
<del> this._updateDOMProperties(null, props, transaction, isCustomComponentTag);
<add> updateDOMProperties(workInProgress, null, props, transaction, isCustomComponentTag);
<ide> var lazyTree = DOMLazyTree(el);
<del> this._createInitialChildren(transaction, props, context, lazyTree);
<add> createInitialChildren(workInProgress, transaction, props, context, lazyTree);
<ide> mountImage = lazyTree;
<ide> } else {
<del> var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
<del> var tagContent = this._createContentMarkup(transaction, props, context);
<del> if (!tagContent && omittedCloseTags[this._tag]) {
<add> var tagOpen = createOpenTagMarkupAndPutListeners(workInProgress, transaction, props);
<add> var tagContent = createContentMarkup(workInProgress, transaction, props, context);
<add> if (!tagContent && omittedCloseTags[workInProgress._tag]) {
<ide> mountImage = tagOpen + '/>';
<ide> } else {
<ide> mountImage = tagOpen + '>' + tagContent + '</' + type + '>';
<ide> }
<ide> }
<ide>
<del> switch (this._tag) {
<add> switch (workInProgress._tag) {
<ide> case 'input':
<ide> transaction.getReactMountReady().enqueue(
<ide> inputPostMount,
<del> this
<add> workInProgress
<ide> );
<ide> if (props.autoFocus) {
<ide> transaction.getReactMountReady().enqueue(
<ide> AutoFocusUtils.focusDOMComponent,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> case 'textarea':
<ide> transaction.getReactMountReady().enqueue(
<ide> textareaPostMount,
<del> this
<add> workInProgress
<ide> );
<ide> if (props.autoFocus) {
<ide> transaction.getReactMountReady().enqueue(
<ide> AutoFocusUtils.focusDOMComponent,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> case 'select':
<ide> if (props.autoFocus) {
<ide> transaction.getReactMountReady().enqueue(
<ide> AutoFocusUtils.focusDOMComponent,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> case 'button':
<ide> if (props.autoFocus) {
<ide> transaction.getReactMountReady().enqueue(
<ide> AutoFocusUtils.focusDOMComponent,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> case 'option':
<ide> transaction.getReactMountReady().enqueue(
<ide> optionPostMount,
<del> this
<add> workInProgress
<ide> );
<ide> break;
<ide> default:
<ide> if (typeof props.onClick === 'function') {
<ide> transaction.getReactMountReady().enqueue(
<ide> trapClickOnNonInteractiveElement,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> ReactDOMComponent.Mixin = {
<ide> return mountImage;
<ide> },
<ide>
<del> /**
<del> * Creates markup for the open tag and all attributes.
<del> *
<del> * This method has side effects because events get registered.
<del> *
<del> * Iterating over object properties is faster than iterating over arrays.
<del> * @see http://jsperf.com/obj-vs-arr-iteration
<del> *
<del> * @private
<del> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {object} props
<del> * @return {string} Markup of opening tag.
<del> */
<del> _createOpenTagMarkupAndPutListeners: function(transaction, props) {
<del> var ret = '<' + this._currentElement.type;
<del>
<del> for (var propKey in props) {
<del> if (!props.hasOwnProperty(propKey)) {
<del> continue;
<del> }
<del> var propValue = props[propKey];
<del> if (propValue == null) {
<del> continue;
<del> }
<del> if (registrationNameModules.hasOwnProperty(propKey)) {
<del> if (propValue) {
<del> enqueuePutListener(this, propKey, propValue, transaction);
<del> }
<del> } else {
<del> if (propKey === STYLE) {
<del> if (propValue) {
<del> if (__DEV__) {
<del> // See `_updateDOMProperties`. style block
<del> this._previousStyle = propValue;
<del> }
<del> propValue = this._previousStyleCopy = Object.assign({}, props.style);
<del> }
<del> propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this);
<del> }
<del> var markup = null;
<del> if (this._tag != null && isCustomComponent(this._tag, props)) {
<del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<del> markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
<del> }
<del> } else {
<del> markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
<del> }
<del> if (markup) {
<del> ret += ' ' + markup;
<del> }
<del> }
<del> }
<del>
<del> // For static pages, no need to put React ID and checksum. Saves lots of
<del> // bytes.
<del> if (transaction.renderToStaticMarkup) {
<del> return ret;
<del> }
<del>
<del> if (!this._hostParent) {
<del> ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
<del> }
<del> ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID);
<del> return ret;
<del> },
<del>
<del> /**
<del> * Creates markup for the content between the tags.
<del> *
<del> * @private
<del> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {object} props
<del> * @param {object} context
<del> * @return {string} Content markup.
<del> */
<del> _createContentMarkup: function(transaction, props, context) {
<del> var ret = '';
<del>
<del> // Intentional use of != to avoid catching zero/false.
<del> var innerHTML = props.dangerouslySetInnerHTML;
<del> if (innerHTML != null) {
<del> if (innerHTML.__html != null) {
<del> ret = innerHTML.__html;
<del> }
<del> } else {
<del> var contentToUse =
<del> CONTENT_TYPES[typeof props.children] ? props.children : null;
<del> var childrenToUse = contentToUse != null ? null : props.children;
<del> if (contentToUse != null) {
<del> // TODO: Validate that text is allowed as a child of this node
<del> ret = escapeTextContentForBrowser(contentToUse);
<del> if (__DEV__) {
<del> setAndValidateContentChildDev.call(this, contentToUse);
<del> }
<del> } else if (childrenToUse != null) {
<del> var mountImages = this.mountChildren(
<del> childrenToUse,
<del> transaction,
<del> context
<del> );
<del> ret = mountImages.join('');
<del> }
<del> }
<del> if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
<del> // text/html ignores the first character in these tags if it's a newline
<del> // Prefer to break application/xml over text/html (for now) by adding
<del> // a newline specifically to get eaten by the parser. (Alternately for
<del> // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
<del> // \r is normalized out by HTMLTextAreaElement#value.)
<del> // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
<del> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
<del> // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
<del> // See: Parsing of "textarea" "listing" and "pre" elements
<del> // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
<del> return '\n' + ret;
<del> } else {
<del> return ret;
<del> }
<del> },
<del>
<del> _createInitialChildren: function(transaction, props, context, lazyTree) {
<del> // Intentional use of != to avoid catching zero/false.
<del> var innerHTML = props.dangerouslySetInnerHTML;
<del> if (innerHTML != null) {
<del> if (innerHTML.__html != null) {
<del> DOMLazyTree.queueHTML(lazyTree, innerHTML.__html);
<del> }
<del> } else {
<del> var contentToUse =
<del> CONTENT_TYPES[typeof props.children] ? props.children : null;
<del> var childrenToUse = contentToUse != null ? null : props.children;
<del> // TODO: Validate that text is allowed as a child of this node
<del> if (contentToUse != null) {
<del> // Avoid setting textContent when the text is empty. In IE11 setting
<del> // textContent on a text area will cause the placeholder to not
<del> // show within the textarea until it has been focused and blurred again.
<del> // https://github.com/facebook/react/issues/6731#issuecomment-254874553
<del> if (contentToUse !== '') {
<del> if (__DEV__) {
<del> setAndValidateContentChildDev.call(this, contentToUse);
<del> }
<del> DOMLazyTree.queueText(lazyTree, contentToUse);
<del> }
<del> } else if (childrenToUse != null) {
<del> var mountImages = this.mountChildren(
<del> childrenToUse,
<del> transaction,
<del> context
<del> );
<del> for (var i = 0; i < mountImages.length; i++) {
<del> DOMLazyTree.queueChild(lazyTree, mountImages[i]);
<del> }
<del> }
<del> }
<del> },
<ide>
<ide> /**
<ide> * Receives a next element and updates the component.
<ide> ReactDOMComponent.Mixin = {
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<ide> * @param {object} context
<ide> */
<del> receiveComponent: function(nextElement, transaction, context) {
<del> var prevElement = this._currentElement;
<del> this._currentElement = nextElement;
<del> this.updateComponent(transaction, prevElement, nextElement, context);
<del> },
<add> receiveComponent: function(workInProgress : Fiber, nextElement, transaction, context) {
<add> var prevElement = workInProgress._currentElement;
<add> workInProgress._currentElement = nextElement;
<ide>
<del> /**
<del> * Updates a DOM component after it has already been allocated and
<del> * attached to the DOM. Reconciles the root DOM node, then recurses.
<del> *
<del> * @param {ReactReconcileTransaction} transaction
<del> * @param {ReactElement} prevElement
<del> * @param {ReactElement} nextElement
<del> * @internal
<del> * @overridable
<del> */
<del> updateComponent: function(transaction, prevElement, nextElement, context) {
<ide> var lastProps = prevElement.props;
<del> var nextProps = this._currentElement.props;
<add> var nextProps = workInProgress._currentElement.props;
<ide>
<del> switch (this._tag) {
<add> switch (workInProgress._tag) {
<ide> case 'input':
<del> lastProps = ReactDOMInput.getHostProps(this, lastProps);
<del> nextProps = ReactDOMInput.getHostProps(this, nextProps);
<add> lastProps = ReactDOMFiberInput.getHostProps(workInProgress, lastProps);
<add> nextProps = ReactDOMFiberInput.getHostProps(workInProgress, nextProps);
<ide> break;
<ide> case 'option':
<del> lastProps = ReactDOMOption.getHostProps(this, lastProps);
<del> nextProps = ReactDOMOption.getHostProps(this, nextProps);
<add> lastProps = ReactDOMFiberOption.getHostProps(workInProgress, lastProps);
<add> nextProps = ReactDOMFiberOption.getHostProps(workInProgress, nextProps);
<ide> break;
<ide> case 'select':
<del> lastProps = ReactDOMSelect.getHostProps(this, lastProps);
<del> nextProps = ReactDOMSelect.getHostProps(this, nextProps);
<add> lastProps = ReactDOMFiberSelect.getHostProps(workInProgress, lastProps);
<add> nextProps = ReactDOMFiberSelect.getHostProps(workInProgress, nextProps);
<ide> break;
<ide> case 'textarea':
<del> lastProps = ReactDOMTextarea.getHostProps(this, lastProps);
<del> nextProps = ReactDOMTextarea.getHostProps(this, nextProps);
<add> lastProps = ReactDOMFiberTextarea.getHostProps(workInProgress, lastProps);
<add> nextProps = ReactDOMFiberTextarea.getHostProps(workInProgress, nextProps);
<ide> break;
<ide> default:
<ide> if (typeof lastProps.onClick !== 'function' &&
<ide> typeof nextProps.onClick === 'function') {
<ide> transaction.getReactMountReady().enqueue(
<ide> trapClickOnNonInteractiveElement,
<del> this
<add> workInProgress
<ide> );
<ide> }
<ide> break;
<ide> }
<ide>
<del> assertValidProps(this, nextProps);
<del> var isCustomComponentTag = isCustomComponent(this._tag, nextProps);
<del> this._updateDOMProperties(lastProps, nextProps, transaction, isCustomComponentTag);
<del> this._updateDOMChildren(
<add> assertValidProps(workInProgress, nextProps);
<add> var isCustomComponentTag = isCustomComponent(workInProgress._tag, nextProps);
<add> updateDOMProperties(workInProgress, lastProps, nextProps, transaction, isCustomComponentTag);
<add> updateDOMChildren(
<add> workInProgress,
<ide> lastProps,
<ide> nextProps,
<ide> transaction,
<ide> context
<ide> );
<ide>
<del> switch (this._tag) {
<add> switch (workInProgress._tag) {
<ide> case 'input':
<ide> // Update the wrapper around inputs *after* updating props. This has to
<del> // happen after `_updateDOMProperties`. Otherwise HTML5 input validations
<add> // happen after `updateDOMProperties`. Otherwise HTML5 input validations
<ide> // raise warnings and prevent the new value from being assigned.
<del> ReactDOMInput.updateWrapper(this);
<add> ReactDOMFiberInput.updateWrapper(workInProgress);
<ide> break;
<ide> case 'textarea':
<del> ReactDOMTextarea.updateWrapper(this);
<add> ReactDOMFiberTextarea.updateWrapper(workInProgress);
<ide> break;
<ide> case 'select':
<ide> // <select> value update needs to occur after <option> children
<ide> // reconciliation
<del> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
<add> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, workInProgress);
<ide> break;
<ide> }
<ide> },
<ide>
<ide> /**
<del> * Reconciles the properties by detecting differences in property values and
<del> * updating the DOM as necessary. This function is probably the single most
<del> * critical path for performance optimization.
<del> *
<del> * TODO: Benchmark whether checking for changed values in memory actually
<del> * improves performance (especially statically positioned elements).
<del> * TODO: Benchmark the effects of putting this at the top since 99% of props
<del> * do not change for a given reconciliation.
<del> * TODO: Benchmark areas that can be improved with caching.
<del> *
<del> * @private
<del> * @param {object} lastProps
<del> * @param {object} nextProps
<del> * @param {?DOMElement} node
<del> */
<del> _updateDOMProperties: function(
<del> lastProps,
<del> nextProps,
<del> transaction,
<del> isCustomComponentTag
<del> ) {
<del> var propKey;
<del> var styleName;
<del> var styleUpdates;
<del> for (propKey in lastProps) {
<del> if (nextProps.hasOwnProperty(propKey) ||
<del> !lastProps.hasOwnProperty(propKey) ||
<del> lastProps[propKey] == null) {
<del> continue;
<del> }
<del> if (propKey === STYLE) {
<del> var lastStyle = this._previousStyleCopy;
<del> for (styleName in lastStyle) {
<del> if (lastStyle.hasOwnProperty(styleName)) {
<del> styleUpdates = styleUpdates || {};
<del> styleUpdates[styleName] = '';
<del> }
<del> }
<del> this._previousStyleCopy = null;
<del> } else if (registrationNameModules.hasOwnProperty(propKey)) {
<del> if (lastProps[propKey]) {
<del> // Only call deleteListener if there was a listener previously or
<del> // else willDeleteListener gets called when there wasn't actually a
<del> // listener (e.g., onClick={null})
<del> deleteListener(this, propKey);
<del> }
<del> } else if (isCustomComponent(this._tag, lastProps)) {
<del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<del> DOMPropertyOperations.deleteValueForAttribute(
<del> getNode(this),
<del> propKey
<del> );
<del> }
<del> } else if (
<del> DOMProperty.properties[propKey] ||
<del> DOMProperty.isCustomAttribute(propKey)) {
<del> DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
<del> }
<del> }
<del> for (propKey in nextProps) {
<del> var nextProp = nextProps[propKey];
<del> var lastProp =
<del> propKey === STYLE ? this._previousStyleCopy :
<del> lastProps != null ? lastProps[propKey] : undefined;
<del> if (!nextProps.hasOwnProperty(propKey) ||
<del> nextProp === lastProp ||
<del> nextProp == null && lastProp == null) {
<del> continue;
<del> }
<del> if (propKey === STYLE) {
<del> if (nextProp) {
<del> if (__DEV__) {
<del> checkAndWarnForMutatedStyle(
<del> this._previousStyleCopy,
<del> this._previousStyle,
<del> this
<del> );
<del> this._previousStyle = nextProp;
<del> }
<del> nextProp = this._previousStyleCopy = Object.assign({}, nextProp);
<del> } else {
<del> this._previousStyleCopy = null;
<del> }
<del> if (lastProp) {
<del> // Unset styles on `lastProp` but not on `nextProp`.
<del> for (styleName in lastProp) {
<del> if (lastProp.hasOwnProperty(styleName) &&
<del> (!nextProp || !nextProp.hasOwnProperty(styleName))) {
<del> styleUpdates = styleUpdates || {};
<del> styleUpdates[styleName] = '';
<del> }
<del> }
<del> // Update styles that changed since `lastProp`.
<del> for (styleName in nextProp) {
<del> if (nextProp.hasOwnProperty(styleName) &&
<del> lastProp[styleName] !== nextProp[styleName]) {
<del> styleUpdates = styleUpdates || {};
<del> styleUpdates[styleName] = nextProp[styleName];
<del> }
<del> }
<del> } else {
<del> // Relies on `updateStylesByID` not mutating `styleUpdates`.
<del> styleUpdates = nextProp;
<del> }
<del> } else if (registrationNameModules.hasOwnProperty(propKey)) {
<del> if (nextProp) {
<del> enqueuePutListener(this, propKey, nextProp, transaction);
<del> } else if (lastProp) {
<del> deleteListener(this, propKey);
<del> }
<del> } else if (isCustomComponentTag) {
<del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
<del> DOMPropertyOperations.setValueForAttribute(
<del> getNode(this),
<del> propKey,
<del> nextProp
<del> );
<del> }
<del> } else if (
<del> DOMProperty.properties[propKey] ||
<del> DOMProperty.isCustomAttribute(propKey)) {
<del> var node = getNode(this);
<del> // If we're updating to null or undefined, we should remove the property
<del> // from the DOM node instead of inadvertently setting to a string. This
<del> // brings us in line with the same behavior we have on initial render.
<del> if (nextProp != null) {
<del> DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
<del> } else {
<del> DOMPropertyOperations.deleteValueForProperty(node, propKey);
<del> }
<del> }
<del> }
<del> if (styleUpdates) {
<del> CSSPropertyOperations.setValueForStyles(
<del> getNode(this),
<del> styleUpdates,
<del> this
<del> );
<del> }
<del> },
<del>
<del> /**
<del> * Reconciles the children with the various properties that affect the
<del> * children content.
<del> *
<del> * @param {object} lastProps
<del> * @param {object} nextProps
<del> * @param {ReactReconcileTransaction} transaction
<del> * @param {object} context
<del> */
<del> _updateDOMChildren: function(lastProps, nextProps, transaction, context) {
<del> var lastContent =
<del> CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
<del> var nextContent =
<del> CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
<del>
<del> var lastHtml =
<del> lastProps.dangerouslySetInnerHTML &&
<del> lastProps.dangerouslySetInnerHTML.__html;
<del> var nextHtml =
<del> nextProps.dangerouslySetInnerHTML &&
<del> nextProps.dangerouslySetInnerHTML.__html;
<del>
<del> // Note the use of `!=` which checks for null or undefined.
<del> var lastChildren = lastContent != null ? null : lastProps.children;
<del> var nextChildren = nextContent != null ? null : nextProps.children;
<del>
<del> // If we're switching from children to content/html or vice versa, remove
<del> // the old content
<del> var lastHasContentOrHtml = lastContent != null || lastHtml != null;
<del> var nextHasContentOrHtml = nextContent != null || nextHtml != null;
<del> if (lastChildren != null && nextChildren == null) {
<del> this.updateChildren(null, transaction, context);
<del> } else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
<del> this.updateTextContent('');
<del> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
<del> }
<del> }
<del>
<del> if (nextContent != null) {
<del> if (lastContent !== nextContent) {
<del> this.updateTextContent('' + nextContent);
<del> if (__DEV__) {
<del> setAndValidateContentChildDev.call(this, nextContent);
<del> }
<del> }
<del> } else if (nextHtml != null) {
<del> if (lastHtml !== nextHtml) {
<del> this.updateMarkup('' + nextHtml);
<del> }
<del> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(this._debugID, []);
<del> }
<del> } else if (nextChildren != null) {
<del> if (__DEV__) {
<del> setAndValidateContentChildDev.call(this, null);
<del> }
<del>
<del> this.updateChildren(nextChildren, transaction, context);
<del> }
<del> },
<del>
<del> getHostNode: function() {
<del> return getNode(this);
<del> },
<del>
<del> /**
<del> * Destroys all event registrations for this instance. Does not remove from
<add> * Destroys all event registrations for workInProgress instance. Does not remove from
<ide> * the DOM. That must be done by the parent.
<ide> *
<ide> * @internal
<ide> */
<ide> unmountComponent: function(safely, skipLifecycle) {
<del> switch (this._tag) {
<add> switch (workInProgress._tag) {
<ide> case 'audio':
<ide> case 'form':
<ide> case 'iframe':
<ide> ReactDOMComponent.Mixin = {
<ide> case 'object':
<ide> case 'source':
<ide> case 'video':
<del> var listeners = this._wrapperState.listeners;
<add> var listeners = workInProgress._wrapperState.listeners;
<ide> if (listeners) {
<ide> for (var i = 0; i < listeners.length; i++) {
<ide> listeners[i].remove();
<ide> ReactDOMComponent.Mixin = {
<ide> break;
<ide> case 'input':
<ide> case 'textarea':
<del> inputValueTracking.stopTracking(this);
<add> inputValueTracking.stopTracking(workInProgress);
<ide> break;
<ide> case 'html':
<ide> case 'head':
<ide> ReactDOMComponent.Mixin = {
<ide> false,
<ide> '<%s> tried to unmount. Because of cross-browser quirks it is ' +
<ide> 'impossible to unmount some top-level components (eg <html>, ' +
<del> '<head>, and <body>) reliably and efficiently. To fix this, have a ' +
<add> '<head>, and <body>) reliably and efficiently. To fix workInProgress, have a ' +
<ide> 'single top-level component that never unmounts render these ' +
<ide> 'elements.',
<del> this._tag
<add> workInProgress._tag
<ide> );
<ide> break;
<ide> }
<ide>
<del> this.unmountChildren(safely, skipLifecycle);
<del> ReactDOMComponentTree.uncacheNode(this);
<del> EventPluginHub.deleteAllListeners(this);
<del> this._rootNodeID = 0;
<del> this._domID = 0;
<del> this._wrapperState = null;
<add> workInProgress.unmountChildren(safely, skipLifecycle);
<add> ReactDOMComponentTree.uncacheNode(workInProgress);
<add> EventPluginHub.deleteAllListeners(workInProgress);
<add> workInProgress._rootNodeID = 0;
<add> workInProgress._domID = 0;
<add> workInProgress._wrapperState = null;
<ide>
<ide> if (__DEV__) {
<del> setAndValidateContentChildDev.call(this, null);
<add> setAndValidateContentChildDev.call(workInProgress, null);
<ide> }
<ide> },
<ide>
<del> restoreControlledState: function() {
<del> switch (this._tag) {
<add> restoreControlledState: function(finishedWork : Fiber) {
<add> switch (finishedWork.type) {
<ide> case 'input':
<del> ReactDOMInput.restoreControlledState(this);
<add> ReactDOMFiberInput.restoreControlledState(finishedWork);
<ide> return;
<ide> case 'textarea':
<del> ReactDOMTextarea.restoreControlledState(this);
<add> ReactDOMFiberTextarea.restoreControlledState(finishedWork);
<ide> return;
<ide> case 'select':
<del> ReactDOMSelect.restoreControlledState(this);
<add> ReactDOMFiberSelect.restoreControlledState(finishedWork);
<ide> return;
<ide> }
<ide> },
<ide>
<del> getPublicInstance: function() {
<del> return getNode(this);
<add> getPublicInstance: function(fiber : Fiber) {
<add> // If we add wrappers, this could be something deeper.
<add> return fiber.stateNode;
<ide> },
<ide>
<ide> };
<ide>
<del>Object.assign(
<del> ReactDOMComponent.prototype,
<del> ReactDOMComponent.Mixin,
<del> ReactMultiChild
<del>);
<del>
<del>module.exports = ReactDOMComponent;
<add>module.exports = ReactDOMFiberComponent;
<ide><path>src/renderers/dom/fiber/wrappers/ReactDOMFiberInput.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactDOMFiberInput
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide><path>src/renderers/dom/fiber/wrappers/ReactDOMFiberOption.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactDOMFiberOption
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide><path>src/renderers/dom/fiber/wrappers/ReactDOMFiberSelect.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactDOMFiberSelect
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide><path>src/renderers/dom/fiber/wrappers/ReactDOMFiberTextarea.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule ReactDOMFiberTextarea
<add> * @flow
<ide> */
<ide>
<ide> 'use strict'; | 5 |
Ruby | Ruby | change description of basicrendering#render | 8c8fb895bbe8e4370922283356f62681170748f4 | <ide><path>actionpack/lib/action_controller/metal/rendering.rb
<ide> module ActionController
<ide> module BasicRendering
<ide> extend ActiveSupport::Concern
<ide>
<del> # Render template to response_body
<add> # Render text or nothing (empty string) to response_body
<ide> # :api: public
<ide> def render(*args, &block)
<ide> super(*args, &block) | 1 |
Python | Python | unify polynomial power functions | ddbc31c2d71285f426dc16fab8ac2e00ffe6c1f8 | <ide><path>numpy/polynomial/chebyshev.py
<ide> def chebpow(c, pow, maxpower=16):
<ide> array([15.5, 22. , 16. , ..., 12.5, 12. , 8. ])
<ide>
<ide> """
<add> # note: this is more efficient than `pu._pow(chebmul, c1, c2)`, as it
<add> # avoids converting between z and c series repeatedly
<add>
<ide> # c is a trimmed copy
<ide> [c] = pu.as_series([c])
<ide> power = int(pow)
<ide><path>numpy/polynomial/hermite.py
<ide> def hermpow(c, pow, maxpower=16):
<ide> array([81., 52., 82., 12., 9.])
<ide>
<ide> """
<del> # c is a trimmed copy
<del> [c] = pu.as_series([c])
<del> power = int(pow)
<del> if power != pow or power < 0:
<del> raise ValueError("Power must be a non-negative integer.")
<del> elif maxpower is not None and power > maxpower:
<del> raise ValueError("Power is too large")
<del> elif power == 0:
<del> return np.array([1], dtype=c.dtype)
<del> elif power == 1:
<del> return c
<del> else:
<del> # This can be made more efficient by using powers of two
<del> # in the usual way.
<del> prd = c
<del> for i in range(2, power + 1):
<del> prd = hermmul(prd, c)
<del> return prd
<add> return pu._pow(hermmul, c, pow, maxpower)
<ide>
<ide>
<ide> def hermder(c, m=1, scl=1, axis=0):
<ide><path>numpy/polynomial/hermite_e.py
<ide> def hermepow(c, pow, maxpower=16):
<ide> array([23., 28., 46., 12., 9.])
<ide>
<ide> """
<del> # c is a trimmed copy
<del> [c] = pu.as_series([c])
<del> power = int(pow)
<del> if power != pow or power < 0:
<del> raise ValueError("Power must be a non-negative integer.")
<del> elif maxpower is not None and power > maxpower:
<del> raise ValueError("Power is too large")
<del> elif power == 0:
<del> return np.array([1], dtype=c.dtype)
<del> elif power == 1:
<del> return c
<del> else:
<del> # This can be made more efficient by using powers of two
<del> # in the usual way.
<del> prd = c
<del> for i in range(2, power + 1):
<del> prd = hermemul(prd, c)
<del> return prd
<add> return pu._pow(hermemul, c, pow, maxpower)
<ide>
<ide>
<ide> def hermeder(c, m=1, scl=1, axis=0):
<ide><path>numpy/polynomial/laguerre.py
<ide> def lagpow(c, pow, maxpower=16):
<ide> array([ 14., -16., 56., -72., 54.])
<ide>
<ide> """
<del> # c is a trimmed copy
<del> [c] = pu.as_series([c])
<del> power = int(pow)
<del> if power != pow or power < 0:
<del> raise ValueError("Power must be a non-negative integer.")
<del> elif maxpower is not None and power > maxpower:
<del> raise ValueError("Power is too large")
<del> elif power == 0:
<del> return np.array([1], dtype=c.dtype)
<del> elif power == 1:
<del> return c
<del> else:
<del> # This can be made more efficient by using powers of two
<del> # in the usual way.
<del> prd = c
<del> for i in range(2, power + 1):
<del> prd = lagmul(prd, c)
<del> return prd
<add> return pu._pow(lagmul, c, pow, maxpower)
<ide>
<ide>
<ide> def lagder(c, m=1, scl=1, axis=0):
<ide><path>numpy/polynomial/legendre.py
<ide> def legpow(c, pow, maxpower=16):
<ide> --------
<ide>
<ide> """
<del> # c is a trimmed copy
<del> [c] = pu.as_series([c])
<del> power = int(pow)
<del> if power != pow or power < 0:
<del> raise ValueError("Power must be a non-negative integer.")
<del> elif maxpower is not None and power > maxpower:
<del> raise ValueError("Power is too large")
<del> elif power == 0:
<del> return np.array([1], dtype=c.dtype)
<del> elif power == 1:
<del> return c
<del> else:
<del> # This can be made more efficient by using powers of two
<del> # in the usual way.
<del> prd = c
<del> for i in range(2, power + 1):
<del> prd = legmul(prd, c)
<del> return prd
<add> return pu._pow(legmul, c, pow, maxpower)
<ide>
<ide>
<ide> def legder(c, m=1, scl=1, axis=0):
<ide><path>numpy/polynomial/polynomial.py
<ide> def polypow(c, pow, maxpower=None):
<ide> array([ 1., 4., 10., 12., 9.])
<ide>
<ide> """
<del> # c is a trimmed copy
<del> [c] = pu.as_series([c])
<del> power = int(pow)
<del> if power != pow or power < 0:
<del> raise ValueError("Power must be a non-negative integer.")
<del> elif maxpower is not None and power > maxpower:
<del> raise ValueError("Power is too large")
<del> elif power == 0:
<del> return np.array([1], dtype=c.dtype)
<del> elif power == 1:
<del> return c
<del> else:
<del> # This can be made more efficient by using powers of two
<del> # in the usual way.
<del> prd = c
<del> for i in range(2, power + 1):
<del> prd = np.convolve(prd, c)
<del> return prd
<add> # note: this is more efficient than `pu._pow(polymul, c1, c2)`, as it
<add> # avoids calling `as_series` repeatedly
<add> return pu._pow(np.convolve, c, pow, maxpower)
<ide>
<ide>
<ide> def polyder(c, m=1, scl=1, axis=0):
<ide><path>numpy/polynomial/polyutils.py
<ide> def _fit(vander_f, x, y, deg, rcond=None, full=False, w=None):
<ide> return c
<ide>
<ide>
<add>def _pow(mul_f, c, pow, maxpower):
<add> """
<add> Helper function used to implement the ``<type>pow`` functions.
<add>
<add> Parameters
<add> ----------
<add> vander_f : function(array_like, int) -> ndarray
<add> The 1d vander function, such as ``polyvander``
<add> pow, maxpower :
<add> See the ``<type>pow`` functions for more detail
<add> mul_f : function(array_like, array_like) -> ndarray
<add> The ``<type>mul`` function, such as ``polymul``
<add> """
<add> # c is a trimmed copy
<add> [c] = as_series([c])
<add> power = int(pow)
<add> if power != pow or power < 0:
<add> raise ValueError("Power must be a non-negative integer.")
<add> elif maxpower is not None and power > maxpower:
<add> raise ValueError("Power is too large")
<add> elif power == 0:
<add> return np.array([1], dtype=c.dtype)
<add> elif power == 1:
<add> return c
<add> else:
<add> # This can be made more efficient by using powers of two
<add> # in the usual way.
<add> prd = c
<add> for i in range(2, power + 1):
<add> prd = mul_f(prd, c)
<add> return prd
<add>
<add>
<ide> def _deprecate_as_int(x, desc):
<ide> """
<ide> Like `operator.index`, but emits a deprecation warning when passed a float | 7 |
Python | Python | add chrome timeline support in tensorflow | e74a37438b5389ae19eb61b431859f9789100874 | <ide><path>keras/backend/tensorflow_backend.py
<ide> from tensorflow.python.ops import variables
<ide>
<ide> from collections import defaultdict
<add>import inspect
<ide> import numpy as np
<ide> import os
<ide> import warnings
<ide> class Function(object):
<ide> name: a name to help users identify what this function does.
<ide> """
<ide>
<del> def __init__(self, inputs, outputs, updates=None, name=None):
<add> def __init__(self, inputs, outputs, updates=None, name=None, **session_kwargs):
<ide> updates = updates or []
<ide> if not isinstance(inputs, (list, tuple)):
<ide> raise TypeError('`inputs` to a TensorFlow backend function '
<ide> def __init__(self, inputs, outputs, updates=None, name=None):
<ide> updates_ops.append(update)
<ide> self.updates_op = tf.group(*updates_ops)
<ide> self.name = name
<add> self.session_kwargs = session_kwargs
<ide>
<ide> def __call__(self, inputs):
<ide> if not isinstance(inputs, (list, tuple)):
<ide> def __call__(self, inputs):
<ide> feed_dict[tensor] = value
<ide> session = get_session()
<ide> updated = session.run(self.outputs + [self.updates_op],
<del> feed_dict=feed_dict)
<add> feed_dict=feed_dict,
<add> **self.session_kwargs)
<ide> return updated[:len(self.outputs)]
<ide>
<ide>
<ide> def function(inputs, outputs, updates=None, **kwargs):
<ide> inputs: List of placeholder tensors.
<ide> outputs: List of output tensors.
<ide> updates: List of update ops.
<del> **kwargs: Not used with TensorFlow.
<add> **kwargs: Passed to `tf.Session.run`.
<ide>
<ide> # Returns
<ide> Output values as Numpy arrays.
<add>
<add> # Raises
<add> ValueError: if invalid kwargs are passed in.
<ide> """
<ide> if kwargs:
<del> msg = [
<del> 'Expected no kwargs, you passed %s' % len(kwargs),
<del> 'kwargs passed to function are ignored with Tensorflow backend'
<del> ]
<del> warnings.warn('\n'.join(msg))
<del> return Function(inputs, outputs, updates=updates)
<add> for key in kwargs.keys():
<add> if (key not in inspect.getargspec(tf.Session.run)[0] and
<add> key not in inspect.getargspec(Function.__init__)[0]):
<add> msg = 'Invalid argument "%s" passed to K.function with Tensorflow backend' % key
<add> raise ValueError(msg)
<add> return Function(inputs, outputs, updates=updates, **kwargs)
<ide>
<ide>
<ide> def gradients(loss, variables):
<ide><path>keras/backend/theano_backend.py
<ide> def function(inputs, outputs, updates=[], **kwargs):
<ide> function_args = inspect.getargspec(theano.function)[0]
<ide> for key in kwargs.keys():
<ide> if key not in function_args:
<del> msg = 'Invalid argument "%s" passed to K.function' % key
<add> msg = 'Invalid argument "%s" passed to K.function with Theano backend' % key
<ide> raise ValueError(msg)
<ide> return Function(inputs, outputs, updates=updates, **kwargs)
<ide>
<ide><path>keras/engine/training.py
<ide> def compile(self, optimizer, loss, metrics=None, loss_weights=None,
<ide> `sample_weight_mode` on each output by passing a
<ide> dictionary or a list of modes.
<ide> **kwargs: when using the Theano backend, these arguments
<del> are passed into K.function. Ignored for Tensorflow backend.
<add> are passed into K.function. When using the Tensorflow backend,
<add> these arguments are passed into `tf.Session.run`.
<ide>
<ide> # Raises
<ide> ValueError: In case of invalid arguments for
<ide><path>keras/models.py
<ide> def compile(self, optimizer, loss,
<ide> sample weighting (2D weights), set this to "temporal".
<ide> "None" defaults to sample-wise weights (1D).
<ide> **kwargs: for Theano backend, these are passed into K.function.
<del> Ignored for Tensorflow backend.
<add> When using the Tensorflow backend, these are passed into
<add> `tf.Session.run`.
<ide>
<ide> # Example
<ide> ```python | 4 |
Go | Go | build types and unsupported stubs everywhere | 6f1553625dbb1adfe87f5a42c1f2f4ca007da5a7 | <ide><path>daemon/graphdriver/quota/projectquota_unsupported.go
<del>// +build linux,exclude_disk_quota linux,!cgo
<add>// +build linux,exclude_disk_quota linux,!cgo !linux
<ide>
<ide> package quota // import "github.com/docker/docker/daemon/graphdriver/quota"
<ide>
<ide><path>daemon/graphdriver/quota/types.go
<del>// +build linux
<del>
<ide> package quota // import "github.com/docker/docker/daemon/graphdriver/quota"
<ide>
<ide> import "sync" | 2 |
Text | Text | apply suggestions from code review | 1cf64e6d8d779e533a424fe4f39139977002acba | <ide><path>README.md
<ide> With Ember, you get all of these things:
<ide> * [**Flexibility**](https://guides.emberjs.com/release/models/customizing-adapters/) Use _**any**_ backend stack with your Ember apps, thanks to the flexibility of adapters and serializers.
<ide> * [**Autotracking**](https://guides.emberjs.com/release/in-depth-topics/autotracking-in-depth/) - Ember's reactivity model makes it easier to decide what to automatically update, and when.
<ide> * [**Bytecode Templates**](https://yehudakatz.com/2017/04/05/the-glimmer-vm-boots-fast-and-stays-fast/) and other compile-time optimizations.
<del>* [**Zero config apps**](https://guides.emberjs.com/release/configuring-ember/) - With strong defaults, you may never need to configure anything in your app, but the options are there if you need it!
<del>* [**Quality addon ecosystem**](https://emberobserver.com/) - high-quality, rated addons with the ability to [search by source code](https://emberobserver.com/code-search?codeQuery=task). Many require no additional configuration, making it easier than ever to supercharge your apps.
<add>* [**Zero Config Apps**](https://guides.emberjs.com/release/configuring-ember/) - With strong defaults, you may never need to configure anything in your app, but the options are there if you need it!
<add>* [**Quality Addon Ecosystem**](https://emberobserver.com/) - high-quality, rated addons with the ability to [search by source code](https://emberobserver.com/code-search?codeQuery=task). Many require no additional configuration, making it easier than ever to supercharge your apps.
<ide>
<ide>
<ide> | 1 |
Ruby | Ruby | reduce minimum clt version | 50c1fea4ea9ca8067e194db5918fbf5a7f5c3ca1 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide> def minimum_version
<ide> case MacOS.version
<ide> when "10.12" then "8.0.0"
<del> else "4.0.0"
<add> else "1.0.0"
<ide> end
<ide> end
<ide> | 1 |
Text | Text | add note about pip being required | c4aed2fc83c3c338b39b0fc3293168ef92669e35 | <ide><path>BUILDING.md
<ide> The Node.js project supports Python >= 3 for building and testing.
<ide>
<ide> #### Unix prerequisites
<ide>
<del>* `gcc` and `g++` >= 8.3 or newer, or
<add>* `gcc` and `g++` >= 8.3 or newer
<ide> * GNU Make 3.81 or newer
<ide> * Python 3.6, 3.7, 3.8, 3.9, or 3.10 (see note above)
<add> * For test coverage, your Python installation must include pip.
<ide>
<ide> Installation via Linux package manager can be achieved with:
<ide>
<del>* Ubuntu, Debian: `sudo apt-get install python3 g++ make`
<del>* Fedora: `sudo dnf install python3 gcc-c++ make`
<del>* CentOS and RHEL: `sudo yum install python3 gcc-c++ make`
<del>* OpenSUSE: `sudo zypper install python3 gcc-c++ make`
<del>* Arch Linux, Manjaro: `sudo pacman -S python gcc make`
<add>* Ubuntu, Debian: `sudo apt-get install python3 g++ make python3-pip`
<add>* Fedora: `sudo dnf install python3 gcc-c++ make python3-pip`
<add>* CentOS and RHEL: `sudo yum install python3 gcc-c++ make python3-pip`
<add>* OpenSUSE: `sudo zypper install python3 gcc-c++ make python3-pip`
<add>* Arch Linux, Manjaro: `sudo pacman -S python gcc make python-pip`
<ide>
<ide> FreeBSD and OpenBSD users may also need to install `libexecinfo`.
<ide>
<ide> #### macOS prerequisites
<ide>
<ide> * Xcode Command Line Tools >= 11 for macOS
<ide> * Python 3.6, 3.7, 3.8, 3.9, or 3.10 (see note above)
<add> * For test coverage, your Python installation must include pip.
<ide>
<ide> macOS users can install the `Xcode Command Line Tools` by running
<ide> `xcode-select --install`. Alternatively, if you already have the full Xcode | 1 |
Ruby | Ruby | remove unnecessary `compact` | 269a184c1962e90edcca47515833cb7eef0aaa41 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def connection_pool_names # :nodoc:
<ide> end
<ide>
<ide> def connection_pool_list
<del> owner_to_pool_manager.values.compact.flat_map { |m| m.pool_configs.map(&:pool) }
<add> owner_to_pool_manager.values.flat_map { |m| m.pool_configs.map(&:pool) }
<ide> end
<ide> alias :connection_pools :connection_pool_list
<ide> | 1 |
PHP | PHP | use $this instead | 11244ffba32e1e7c6c82c2ef7c0c403210ff1ffd | <ide><path>src/Console/ConsoleOptionParser.php
<ide> public function __construct($command = null, $defaultOptions = true)
<ide> *
<ide> * @param string|null $command The command name this parser is for. The command name is used for generating help.
<ide> * @param bool $defaultOptions Whether you want the verbose and quiet options set.
<del> * @return \Cake\Console\ConsoleOptionParser
<add> * @return $this
<ide> */
<ide> public static function create($command, $defaultOptions = true)
<ide> {
<ide> public static function create($command, $defaultOptions = true)
<ide> *
<ide> * @param array $spec The spec to build the OptionParser with.
<ide> * @param bool $defaultOptions Whether you want the verbose and quiet options set.
<del> * @return \Cake\Console\ConsoleOptionParser
<add> * @return $this
<ide> */
<ide> public static function buildFromArray($spec, $defaultOptions = true)
<ide> {
<ide> public function addOption($name, array $options = [])
<ide> * Remove an option from the option parser.
<ide> *
<ide> * @param string $name The option name to remove.
<del> * @return \Cake\Console\ConsoleOptionParser this
<add> * @return $this
<ide> */
<ide> public function removeOption($name)
<ide> { | 1 |
Javascript | Javascript | add looprotect error to 'output' | fb8a5d7af7d5c5b88829be7dc63ea373cf4ee86b | <ide><path>client/rechallenge/transformers.js
<ide> import { updateContents } from '../../common/utils/polyvinyl';
<ide>
<ide> const babelOptions = { presets: [ presetEs2015, presetReact ] };
<ide> loopProtect.hit = function hit(line) {
<del> var err = 'Error: Exiting potential infinite loop at line ' +
<add> var err = 'Exiting potential infinite loop at line ' +
<ide> line +
<del> '. To disable loop protection, write: \n\\/\\/ noprotect\nas the first' +
<del> 'line. Beware that if you do have an infinite loop in your code' +
<add> '. To disable loop protection, write: \n\/\/ noprotect\nas the first ' +
<add> 'line. Beware that if you do have an infinite loop in your code, ' +
<ide> 'this will crash your browser.';
<del> console.error(err);
<add> throw new Error(err);
<ide> };
<ide>
<ide> const transformersForHtmlJS = { | 1 |
Ruby | Ruby | move global methods into `kernel` module | e5899a6101320cb0ed10ddf0434802d752b2c78b | <ide><path>Library/Homebrew/utils.rb
<ide> require "tap_constants"
<ide> require "time"
<ide>
<del>def require?(path)
<del> return false if path.nil?
<del>
<del> require path
<del> true
<del>rescue LoadError => e
<del> # we should raise on syntax errors but not if the file doesn't exist.
<del> raise unless e.message.include?(path)
<del>end
<del>
<del>def ohai_title(title)
<del> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
<del> Formatter.headline(title, color: :blue)
<del>end
<del>
<del>def ohai(title, *sput)
<del> puts ohai_title(title)
<del> puts sput
<del>end
<del>
<del>def odebug(title, *sput)
<del> return unless ARGV.debug?
<del>
<del> puts Formatter.headline(title, color: :magenta)
<del> puts sput unless sput.empty?
<del>end
<del>
<del>def oh1(title, options = {})
<del> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose? && options.fetch(:truncate, :auto) == :auto
<del> puts Formatter.headline(title, color: :green)
<del>end
<del>
<del># Print a warning (do this rarely)
<del>def opoo(message)
<del> $stderr.puts Formatter.warning(message, label: "Warning")
<del>end
<del>
<del>def onoe(message)
<del> $stderr.puts Formatter.error(message, label: "Error")
<del>end
<del>
<del>def ofail(error)
<del> onoe error
<del> Homebrew.failed = true
<del>end
<del>
<del>def odie(error)
<del> onoe error
<del> exit 1
<del>end
<del>
<del>def odeprecated(method, replacement = nil, disable: false, disable_on: nil, caller: send(:caller))
<del> replacement_message = if replacement
<del> "Use #{replacement} instead."
<del> else
<del> "There is no replacement."
<del> end
<del>
<del> unless disable_on.nil?
<del> if disable_on > Time.now
<del> will_be_disabled_message = " and will be disabled on #{disable_on.strftime("%Y-%m-%d")}"
<del> else
<del> disable = true
<del> end
<del> end
<del>
<del> verb = if disable
<del> "disabled"
<del> else
<del> "deprecated#{will_be_disabled_message}"
<del> end
<del>
<del> # Try to show the most relevant location in message, i.e. (if applicable):
<del> # - Location in a formula.
<del> # - Location outside of 'compat/'.
<del> # - Location of caller of deprecated method (if all else fails).
<del> backtrace = caller
<del>
<del> # Don't throw deprecations at all for cached, .brew or .metadata files.
<del> return if backtrace.any? do |line|
<del> line.include?(HOMEBREW_CACHE) ||
<del> line.include?("/.brew/") ||
<del> line.include?("/.metadata/")
<del> end
<del>
<del> tap_message = nil
<del>
<del> backtrace.each do |line|
<del> next unless match = line.match(HOMEBREW_TAP_PATH_REGEX)
<del>
<del> tap = Tap.fetch(match[:user], match[:repo])
<del> tap_message = +"\nPlease report this to the #{tap} tap"
<del> tap_message += ", or even better, submit a PR to fix it" if replacement
<del> tap_message << ":\n #{line.sub(/^(.*\:\d+)\:.*$/, '\1')}\n\n"
<del> break
<del> end
<del>
<del> message = +"Calling #{method} is #{verb}! #{replacement_message}"
<del> message << tap_message if tap_message
<del> message.freeze
<del>
<del> if ARGV.homebrew_developer? || disable || Homebrew.raise_deprecation_exceptions?
<del> exception = MethodDeprecatedError.new(message)
<del> exception.set_backtrace(backtrace)
<del> raise exception
<del> elsif !Homebrew.auditing?
<del> opoo message
<del> end
<del>end
<del>
<del>def odisabled(method, replacement = nil, options = {})
<del> options = { disable: true, caller: caller }.merge(options)
<del> odeprecated(method, replacement, options)
<del>end
<del>
<del>def pretty_installed(f)
<del> if !$stdout.tty?
<del> f.to_s
<del> elsif Emoji.enabled?
<del> "#{Tty.bold}#{f} #{Formatter.success("✔")}#{Tty.reset}"
<del> else
<del> Formatter.success("#{Tty.bold}#{f} (installed)#{Tty.reset}")
<del> end
<del>end
<del>
<del>def pretty_uninstalled(f)
<del> if !$stdout.tty?
<del> f.to_s
<del> elsif Emoji.enabled?
<del> "#{Tty.bold}#{f} #{Formatter.error("✘")}#{Tty.reset}"
<del> else
<del> Formatter.error("#{Tty.bold}#{f} (uninstalled)#{Tty.reset}")
<del> end
<del>end
<del>
<del>def pretty_duration(s)
<del> s = s.to_i
<del> res = +""
<del>
<del> if s > 59
<del> m = s / 60
<del> s %= 60
<del> res = +"#{m} #{"minute".pluralize(m)}"
<del> return res.freeze if s.zero?
<del>
<del> res << " "
<del> end
<del>
<del> res << "#{s} #{"second".pluralize(s)}"
<del> res.freeze
<del>end
<del>
<del>def interactive_shell(f = nil)
<del> unless f.nil?
<del> ENV["HOMEBREW_DEBUG_PREFIX"] = f.prefix
<del> ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
<del> end
<del>
<del> if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s)
<del> FileUtils.mkdir_p ENV["HOME"]
<del> FileUtils.touch "#{ENV["HOME"]}/.zshrc"
<del> end
<del>
<del> Process.wait fork { exec ENV["SHELL"] }
<del>
<del> return if $CHILD_STATUS.success?
<del> raise "Aborted due to non-zero exit status (#{$CHILD_STATUS.exitstatus})" if $CHILD_STATUS.exited?
<del>
<del> raise $CHILD_STATUS.inspect
<del>end
<del>
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def inject_dump_stats!(the_module, pattern)
<ide> # rubocop:enable Style/GlobalVars
<ide> end
<ide>
<del>def with_homebrew_path
<del> with_env(PATH: PATH.new(ENV["HOMEBREW_PATH"])) do
<del> yield
<add>module Kernel
<add> def require?(path)
<add> return false if path.nil?
<add>
<add> require path
<add> true
<add> rescue LoadError => e
<add> # we should raise on syntax errors but not if the file doesn't exist.
<add> raise unless e.message.include?(path)
<ide> end
<del>end
<ide>
<del>def with_custom_locale(locale)
<del> with_env(LC_ALL: locale) do
<del> yield
<add> def ohai_title(title)
<add> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
<add> Formatter.headline(title, color: :blue)
<ide> end
<del>end
<ide>
<del># Kernel.system but with exceptions
<del>def safe_system(cmd, *args, **options)
<del> return if Homebrew.system(cmd, *args, **options)
<add> def ohai(title, *sput)
<add> puts ohai_title(title)
<add> puts sput
<add> end
<ide>
<del> raise ErrorDuringExecution.new([cmd, *args], status: $CHILD_STATUS)
<del>end
<add> def odebug(title, *sput)
<add> return unless ARGV.debug?
<ide>
<del># Prints no output
<del>def quiet_system(cmd, *args)
<del> Homebrew._system(cmd, *args) do
<del> # Redirect output streams to `/dev/null` instead of closing as some programs
<del> # will fail to execute if they can't write to an open stream.
<del> $stdout.reopen("/dev/null")
<del> $stderr.reopen("/dev/null")
<add> puts Formatter.headline(title, color: :magenta)
<add> puts sput unless sput.empty?
<ide> end
<del>end
<ide>
<del>def which(cmd, path = ENV["PATH"])
<del> PATH.new(path).each do |p|
<del> begin
<del> pcmd = File.expand_path(cmd, p)
<del> rescue ArgumentError
<del> # File.expand_path will raise an ArgumentError if the path is malformed.
<del> # See https://github.com/Homebrew/legacy-homebrew/issues/32789
<del> next
<del> end
<del> return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
<add> def oh1(title, options = {})
<add> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose? && options.fetch(:truncate, :auto) == :auto
<add> puts Formatter.headline(title, color: :green)
<ide> end
<del> nil
<del>end
<ide>
<del>def which_all(cmd, path = ENV["PATH"])
<del> PATH.new(path).map do |p|
<del> begin
<del> pcmd = File.expand_path(cmd, p)
<del> rescue ArgumentError
<del> # File.expand_path will raise an ArgumentError if the path is malformed.
<del> # See https://github.com/Homebrew/legacy-homebrew/issues/32789
<del> next
<add> # Print a warning (do this rarely)
<add> def opoo(message)
<add> $stderr.puts Formatter.warning(message, label: "Warning")
<add> end
<add>
<add> def onoe(message)
<add> $stderr.puts Formatter.error(message, label: "Error")
<add> end
<add>
<add> def ofail(error)
<add> onoe error
<add> Homebrew.failed = true
<add> end
<add>
<add> def odie(error)
<add> onoe error
<add> exit 1
<add> end
<add>
<add> def odeprecated(method, replacement = nil, disable: false, disable_on: nil, caller: send(:caller))
<add> replacement_message = if replacement
<add> "Use #{replacement} instead."
<add> else
<add> "There is no replacement."
<add> end
<add>
<add> unless disable_on.nil?
<add> if disable_on > Time.now
<add> will_be_disabled_message = " and will be disabled on #{disable_on.strftime("%Y-%m-%d")}"
<add> else
<add> disable = true
<add> end
<add> end
<add>
<add> verb = if disable
<add> "disabled"
<add> else
<add> "deprecated#{will_be_disabled_message}"
<add> end
<add>
<add> # Try to show the most relevant location in message, i.e. (if applicable):
<add> # - Location in a formula.
<add> # - Location outside of 'compat/'.
<add> # - Location of caller of deprecated method (if all else fails).
<add> backtrace = caller
<add>
<add> # Don't throw deprecations at all for cached, .brew or .metadata files.
<add> return if backtrace.any? do |line|
<add> line.include?(HOMEBREW_CACHE) ||
<add> line.include?("/.brew/") ||
<add> line.include?("/.metadata/")
<add> end
<add>
<add> tap_message = nil
<add>
<add> backtrace.each do |line|
<add> next unless match = line.match(HOMEBREW_TAP_PATH_REGEX)
<add>
<add> tap = Tap.fetch(match[:user], match[:repo])
<add> tap_message = +"\nPlease report this to the #{tap} tap"
<add> tap_message += ", or even better, submit a PR to fix it" if replacement
<add> tap_message << ":\n #{line.sub(/^(.*\:\d+)\:.*$/, '\1')}\n\n"
<add> break
<ide> end
<del> Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
<del> end.compact.uniq
<del>end
<ide>
<del>def which_editor
<del> editor = ENV.values_at("HOMEBREW_EDITOR", "HOMEBREW_VISUAL")
<del> .compact
<del> .reject(&:empty?)
<del> .first
<del> return editor if editor
<add> message = +"Calling #{method} is #{verb}! #{replacement_message}"
<add> message << tap_message if tap_message
<add> message.freeze
<ide>
<del> # Find Atom, Sublime Text, Textmate, BBEdit / TextWrangler, or vim
<del> editor = %w[atom subl mate edit vim].find do |candidate|
<del> candidate if which(candidate, ENV["HOMEBREW_PATH"])
<add> if ARGV.homebrew_developer? || disable || Homebrew.raise_deprecation_exceptions?
<add> exception = MethodDeprecatedError.new(message)
<add> exception.set_backtrace(backtrace)
<add> raise exception
<add> elsif !Homebrew.auditing?
<add> opoo message
<add> end
<ide> end
<del> editor ||= "vim"
<ide>
<del> opoo <<~EOS
<del> Using #{editor} because no editor was set in the environment.
<del> This may change in the future, so we recommend setting EDITOR,
<del> or HOMEBREW_EDITOR to your preferred text editor.
<del> EOS
<add> def odisabled(method, replacement = nil, options = {})
<add> options = { disable: true, caller: caller }.merge(options)
<add> odeprecated(method, replacement, options)
<add> end
<ide>
<del> editor
<del>end
<add> def pretty_installed(f)
<add> if !$stdout.tty?
<add> f.to_s
<add> elsif Emoji.enabled?
<add> "#{Tty.bold}#{f} #{Formatter.success("✔")}#{Tty.reset}"
<add> else
<add> Formatter.success("#{Tty.bold}#{f} (installed)#{Tty.reset}")
<add> end
<add> end
<ide>
<del>def exec_editor(*args)
<del> puts "Editing #{args.join "\n"}"
<del> with_homebrew_path { safe_system(*which_editor.shellsplit, *args) }
<del>end
<add> def pretty_uninstalled(f)
<add> if !$stdout.tty?
<add> f.to_s
<add> elsif Emoji.enabled?
<add> "#{Tty.bold}#{f} #{Formatter.error("✘")}#{Tty.reset}"
<add> else
<add> Formatter.error("#{Tty.bold}#{f} (uninstalled)#{Tty.reset}")
<add> end
<add> end
<ide>
<del>def exec_browser(*args)
<del> browser = ENV["HOMEBREW_BROWSER"]
<del> browser ||= OS::PATH_OPEN if defined?(OS::PATH_OPEN)
<del> return unless browser
<add> def pretty_duration(s)
<add> s = s.to_i
<add> res = +""
<ide>
<del> ENV["DISPLAY"] = ENV["HOMEBREW_DISPLAY"]
<add> if s > 59
<add> m = s / 60
<add> s %= 60
<add> res = +"#{m} #{"minute".pluralize(m)}"
<add> return res.freeze if s.zero?
<ide>
<del> safe_system(browser, *args)
<del>end
<add> res << " "
<add> end
<ide>
<del># GZips the given paths, and returns the gzipped paths
<del>def gzip(*paths)
<del> paths.map do |path|
<del> safe_system "gzip", path
<del> Pathname.new("#{path}.gz")
<add> res << "#{s} #{"second".pluralize(s)}"
<add> res.freeze
<ide> end
<del>end
<ide>
<del># Returns array of architectures that the given command or library is built for.
<del>def archs_for_command(cmd)
<del> cmd = which(cmd) unless Pathname.new(cmd).absolute?
<del> Pathname.new(cmd).archs
<del>end
<add> def interactive_shell(f = nil)
<add> unless f.nil?
<add> ENV["HOMEBREW_DEBUG_PREFIX"] = f.prefix
<add> ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
<add> end
<add>
<add> if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s)
<add> FileUtils.mkdir_p ENV["HOME"]
<add> FileUtils.touch "#{ENV["HOME"]}/.zshrc"
<add> end
<add>
<add> Process.wait fork { exec ENV["SHELL"] }
<ide>
<del>def ignore_interrupts(opt = nil)
<del> std_trap = trap("INT") do
<del> puts "One sec, just cleaning up" unless opt == :quietly
<add> return if $CHILD_STATUS.success?
<add> raise "Aborted due to non-zero exit status (#{$CHILD_STATUS.exitstatus})" if $CHILD_STATUS.exited?
<add>
<add> raise $CHILD_STATUS.inspect
<ide> end
<del> yield
<del>ensure
<del> trap("INT", std_trap)
<del>end
<ide>
<del>def capture_stderr
<del> old = $stderr
<del> $stderr = StringIO.new
<del> yield
<del> $stderr.string
<del>ensure
<del> $stderr = old
<del>end
<add> def with_homebrew_path
<add> with_env(PATH: PATH.new(ENV["HOMEBREW_PATH"])) do
<add> yield
<add> end
<add> end
<ide>
<del>def nostdout
<del> if ARGV.verbose?
<del> yield
<del> else
<del> begin
<del> out = $stdout.dup
<del> $stdout.reopen("/dev/null")
<add> def with_custom_locale(locale)
<add> with_env(LC_ALL: locale) do
<ide> yield
<del> ensure
<del> $stdout.reopen(out)
<del> out.close
<ide> end
<ide> end
<del>end
<ide>
<del>def paths
<del> @paths ||= PATH.new(ENV["HOMEBREW_PATH"]).map do |p|
<del> begin
<del> File.expand_path(p).chomp("/")
<del> rescue ArgumentError
<del> onoe "The following PATH component is invalid: #{p}"
<add> # Kernel.system but with exceptions
<add> def safe_system(cmd, *args, **options)
<add> return if Homebrew.system(cmd, *args, **options)
<add>
<add> raise ErrorDuringExecution.new([cmd, *args], status: $CHILD_STATUS)
<add> end
<add>
<add> # Prints no output
<add> def quiet_system(cmd, *args)
<add> Homebrew._system(cmd, *args) do
<add> # Redirect output streams to `/dev/null` instead of closing as some programs
<add> # will fail to execute if they can't write to an open stream.
<add> $stdout.reopen("/dev/null")
<add> $stderr.reopen("/dev/null")
<ide> end
<del> end.uniq.compact
<del>end
<add> end
<ide>
<del>def disk_usage_readable(size_in_bytes)
<del> if size_in_bytes >= 1_073_741_824
<del> size = size_in_bytes.to_f / 1_073_741_824
<del> unit = "GB"
<del> elsif size_in_bytes >= 1_048_576
<del> size = size_in_bytes.to_f / 1_048_576
<del> unit = "MB"
<del> elsif size_in_bytes >= 1_024
<del> size = size_in_bytes.to_f / 1_024
<del> unit = "KB"
<del> else
<del> size = size_in_bytes
<del> unit = "B"
<del> end
<del>
<del> # avoid trailing zero after decimal point
<del> if ((size * 10).to_i % 10).zero?
<del> "#{size.to_i}#{unit}"
<del> else
<del> "#{format("%.1f", size)}#{unit}"
<add> def which(cmd, path = ENV["PATH"])
<add> PATH.new(path).each do |p|
<add> begin
<add> pcmd = File.expand_path(cmd, p)
<add> rescue ArgumentError
<add> # File.expand_path will raise an ArgumentError if the path is malformed.
<add> # See https://github.com/Homebrew/legacy-homebrew/issues/32789
<add> next
<add> end
<add> return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
<add> end
<add> nil
<ide> end
<del>end
<ide>
<del>def number_readable(number)
<del> numstr = number.to_i.to_s
<del> (numstr.size - 3).step(1, -3) { |i| numstr.insert(i, ",") }
<del> numstr
<del>end
<add> def which_all(cmd, path = ENV["PATH"])
<add> PATH.new(path).map do |p|
<add> begin
<add> pcmd = File.expand_path(cmd, p)
<add> rescue ArgumentError
<add> # File.expand_path will raise an ArgumentError if the path is malformed.
<add> # See https://github.com/Homebrew/legacy-homebrew/issues/32789
<add> next
<add> end
<add> Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
<add> end.compact.uniq
<add> end
<ide>
<del># Truncates a text string to fit within a byte size constraint,
<del># preserving character encoding validity. The returned string will
<del># be not much longer than the specified max_bytes, though the exact
<del># shortfall or overrun may vary.
<del>def truncate_text_to_approximate_size(s, max_bytes, options = {})
<del> front_weight = options.fetch(:front_weight, 0.5)
<del> raise "opts[:front_weight] must be between 0.0 and 1.0" if front_weight < 0.0 || front_weight > 1.0
<del> return s if s.bytesize <= max_bytes
<del>
<del> glue = "\n[...snip...]\n"
<del> max_bytes_in = [max_bytes - glue.bytesize, 1].max
<del> bytes = s.dup.force_encoding("BINARY")
<del> glue_bytes = glue.encode("BINARY")
<del> n_front_bytes = (max_bytes_in * front_weight).floor
<del> n_back_bytes = max_bytes_in - n_front_bytes
<del> if n_front_bytes.zero?
<del> front = bytes[1..0]
<del> back = bytes[-max_bytes_in..-1]
<del> elsif n_back_bytes.zero?
<del> front = bytes[0..(max_bytes_in - 1)]
<del> back = bytes[1..0]
<del> else
<del> front = bytes[0..(n_front_bytes - 1)]
<del> back = bytes[-n_back_bytes..-1]
<del> end
<del> out = front + glue_bytes + back
<del> out.force_encoding("UTF-8")
<del> out.encode!("UTF-16", invalid: :replace)
<del> out.encode!("UTF-8")
<del> out
<del>end
<add> def which_editor
<add> editor = ENV.values_at("HOMEBREW_EDITOR", "HOMEBREW_VISUAL")
<add> .compact
<add> .reject(&:empty?)
<add> .first
<add> return editor if editor
<ide>
<del># Calls the given block with the passed environment variables
<del># added to ENV, then restores ENV afterwards.
<del># Example:
<del># <pre>with_env(PATH: "/bin") do
<del># system "echo $PATH"
<del># end</pre>
<del>#
<del># Note that this method is *not* thread-safe - other threads
<del># which happen to be scheduled during the block will also
<del># see these environment variables.
<del>def with_env(hash)
<del> old_values = {}
<del> begin
<del> hash.each do |key, value|
<del> key = key.to_s
<del> old_values[key] = ENV.delete(key)
<del> ENV[key] = value
<add> # Find Atom, Sublime Text, Textmate, BBEdit / TextWrangler, or vim
<add> editor = %w[atom subl mate edit vim].find do |candidate|
<add> candidate if which(candidate, ENV["HOMEBREW_PATH"])
<ide> end
<add> editor ||= "vim"
<add>
<add> opoo <<~EOS
<add> Using #{editor} because no editor was set in the environment.
<add> This may change in the future, so we recommend setting EDITOR,
<add> or HOMEBREW_EDITOR to your preferred text editor.
<add> EOS
<add>
<add> editor
<add> end
<add>
<add> def exec_editor(*args)
<add> puts "Editing #{args.join "\n"}"
<add> with_homebrew_path { safe_system(*which_editor.shellsplit, *args) }
<add> end
<add>
<add> def exec_browser(*args)
<add> browser = ENV["HOMEBREW_BROWSER"]
<add> browser ||= OS::PATH_OPEN if defined?(OS::PATH_OPEN)
<add> return unless browser
<add>
<add> ENV["DISPLAY"] = ENV["HOMEBREW_DISPLAY"]
<ide>
<del> yield if block_given?
<add> safe_system(browser, *args)
<add> end
<add>
<add> # GZips the given paths, and returns the gzipped paths
<add> def gzip(*paths)
<add> paths.map do |path|
<add> safe_system "gzip", path
<add> Pathname.new("#{path}.gz")
<add> end
<add> end
<add>
<add> # Returns array of architectures that the given command or library is built for.
<add> def archs_for_command(cmd)
<add> cmd = which(cmd) unless Pathname.new(cmd).absolute?
<add> Pathname.new(cmd).archs
<add> end
<add>
<add> def ignore_interrupts(opt = nil)
<add> std_trap = trap("INT") do
<add> puts "One sec, just cleaning up" unless opt == :quietly
<add> end
<add> yield
<ide> ensure
<del> ENV.update(old_values)
<add> trap("INT", std_trap)
<ide> end
<del>end
<ide>
<del>def shell_profile
<del> Utils::Shell.profile
<del>end
<add> def capture_stderr
<add> old = $stderr
<add> $stderr = StringIO.new
<add> yield
<add> $stderr.string
<add> ensure
<add> $stderr = old
<add> end
<ide>
<del>def tap_and_name_comparison
<del> proc do |a, b|
<del> if a.include?("/") && !b.include?("/")
<del> 1
<del> elsif !a.include?("/") && b.include?("/")
<del> -1
<add> def nostdout
<add> if ARGV.verbose?
<add> yield
<ide> else
<del> a <=> b
<add> begin
<add> out = $stdout.dup
<add> $stdout.reopen("/dev/null")
<add> yield
<add> ensure
<add> $stdout.reopen(out)
<add> out.close
<add> end
<ide> end
<ide> end
<del>end
<ide>
<del>def command_help_lines(path)
<del> path.read.lines.grep(/^#:/).map { |line| line.slice(2..-1) }
<del>end
<add> def paths
<add> @paths ||= PATH.new(ENV["HOMEBREW_PATH"]).map do |p|
<add> begin
<add> File.expand_path(p).chomp("/")
<add> rescue ArgumentError
<add> onoe "The following PATH component is invalid: #{p}"
<add> end
<add> end.uniq.compact
<add> end
<ide>
<del>def redact_secrets(input, secrets)
<del> secrets.compact
<del> .reduce(input) { |str, secret| str.gsub secret, "******" }
<del> .freeze
<add> def disk_usage_readable(size_in_bytes)
<add> if size_in_bytes >= 1_073_741_824
<add> size = size_in_bytes.to_f / 1_073_741_824
<add> unit = "GB"
<add> elsif size_in_bytes >= 1_048_576
<add> size = size_in_bytes.to_f / 1_048_576
<add> unit = "MB"
<add> elsif size_in_bytes >= 1_024
<add> size = size_in_bytes.to_f / 1_024
<add> unit = "KB"
<add> else
<add> size = size_in_bytes
<add> unit = "B"
<add> end
<add>
<add> # avoid trailing zero after decimal point
<add> if ((size * 10).to_i % 10).zero?
<add> "#{size.to_i}#{unit}"
<add> else
<add> "#{format("%.1f", size)}#{unit}"
<add> end
<add> end
<add>
<add> def number_readable(number)
<add> numstr = number.to_i.to_s
<add> (numstr.size - 3).step(1, -3) { |i| numstr.insert(i, ",") }
<add> numstr
<add> end
<add>
<add> # Truncates a text string to fit within a byte size constraint,
<add> # preserving character encoding validity. The returned string will
<add> # be not much longer than the specified max_bytes, though the exact
<add> # shortfall or overrun may vary.
<add> def truncate_text_to_approximate_size(s, max_bytes, options = {})
<add> front_weight = options.fetch(:front_weight, 0.5)
<add> raise "opts[:front_weight] must be between 0.0 and 1.0" if front_weight < 0.0 || front_weight > 1.0
<add> return s if s.bytesize <= max_bytes
<add>
<add> glue = "\n[...snip...]\n"
<add> max_bytes_in = [max_bytes - glue.bytesize, 1].max
<add> bytes = s.dup.force_encoding("BINARY")
<add> glue_bytes = glue.encode("BINARY")
<add> n_front_bytes = (max_bytes_in * front_weight).floor
<add> n_back_bytes = max_bytes_in - n_front_bytes
<add> if n_front_bytes.zero?
<add> front = bytes[1..0]
<add> back = bytes[-max_bytes_in..-1]
<add> elsif n_back_bytes.zero?
<add> front = bytes[0..(max_bytes_in - 1)]
<add> back = bytes[1..0]
<add> else
<add> front = bytes[0..(n_front_bytes - 1)]
<add> back = bytes[-n_back_bytes..-1]
<add> end
<add> out = front + glue_bytes + back
<add> out.force_encoding("UTF-8")
<add> out.encode!("UTF-16", invalid: :replace)
<add> out.encode!("UTF-8")
<add> out
<add> end
<add>
<add> # Calls the given block with the passed environment variables
<add> # added to ENV, then restores ENV afterwards.
<add> # Example:
<add> # <pre>with_env(PATH: "/bin") do
<add> # system "echo $PATH"
<add> # end</pre>
<add> #
<add> # Note that this method is *not* thread-safe - other threads
<add> # which happen to be scheduled during the block will also
<add> # see these environment variables.
<add> def with_env(hash)
<add> old_values = {}
<add> begin
<add> hash.each do |key, value|
<add> key = key.to_s
<add> old_values[key] = ENV.delete(key)
<add> ENV[key] = value
<add> end
<add>
<add> yield if block_given?
<add> ensure
<add> ENV.update(old_values)
<add> end
<add> end
<add>
<add> def shell_profile
<add> Utils::Shell.profile
<add> end
<add>
<add> def tap_and_name_comparison
<add> proc do |a, b|
<add> if a.include?("/") && !b.include?("/")
<add> 1
<add> elsif !a.include?("/") && b.include?("/")
<add> -1
<add> else
<add> a <=> b
<add> end
<add> end
<add> end
<add>
<add> def command_help_lines(path)
<add> path.read.lines.grep(/^#:/).map { |line| line.slice(2..-1) }
<add> end
<add>
<add> def redact_secrets(input, secrets)
<add> secrets.compact
<add> .reduce(input) { |str, secret| str.gsub secret, "******" }
<add> .freeze
<add> end
<ide> end | 1 |
Python | Python | ignore whitespaces while parsing gufunc signatures | 943729592b380dc58368b6774ad7baa53469466c | <ide><path>numpy/lib/function_base.py
<ide> def disp(mesg, device=None, linefeed=True):
<ide>
<ide>
<ide> # See https://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
<del>_DIMENSION_NAME = r'\w+'
<add>_DIMENSION_NAME = r'\s*\w+\s*'
<ide> _CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME)
<del>_ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST)
<add>_ARGUMENT = r'\s*\({}\s*\)\s*'.format(_CORE_DIMENSION_LIST)
<ide> _ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT)
<ide> _SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST)
<ide>
<ide> def _parse_gufunc_signature(signature):
<ide> if not re.match(_SIGNATURE, signature):
<ide> raise ValueError(
<ide> 'not a valid gufunc signature: {}'.format(signature))
<del> return tuple([tuple(re.findall(_DIMENSION_NAME, arg))
<add> return tuple([tuple([dim.strip() for dim in re.findall(_DIMENSION_NAME, arg)])
<ide> for arg in re.findall(_ARGUMENT, arg_list)]
<ide> for arg_list in signature.split('->'))
<ide> | 1 |
Text | Text | improve formatting of spanish wireframing article | b28caa1b7e8089b23ad15b72e008991c6ccfe2de | <ide><path>guide/spanish/visual-design/wireframing/index.md
<ide> Wireframing es una forma de diseñar una aplicación a nivel estructural. Una es
<ide>
<ide> Encuentre recursos adicionales en Wireframing [aquí](http://www.experienceux.co.uk/faqs/what-is-wireframing/)
<ide>
<del>[
<del>
<ide> ## Herramientas de alambre
<ide>
<del>* * *
<del>
<del>](http://www.experienceux.co.uk/faqs/what-is-wireframing/)
<del>
<del>[](http://www.experienceux.co.uk/faqs/what-is-wireframing/)* [](http://www.experienceux.co.uk/faqs/what-is-wireframing/)[Maravilla](https://marvelapp.com/home)
<del>* [InVision](https://www.invisionapp.com/)
<del>* [Proto App](https://proto.io/)
<del>* [Lucidchart](https://www.lucidchart.com/pages/examples/wireframe_software/)
<del>* [Lápiz](http://pencil.evolus.vn/Default.html/)
<ide>\ No newline at end of file
<add>* [Maravilla](https://marvelapp.com/home)
<add>* [InVision](https://www.invisionapp.com/)
<add>* [Proto App](https://proto.io/)
<add>* [Lucidchart](https://www.lucidchart.com/pages/examples/wireframe_software/)
<add>* [Lápiz](http://pencil.evolus.vn/Default.html/) | 1 |
Go | Go | add newline after warning | bb3d7e1e6543a49fd344e765169265a08a19331a | <ide><path>api/client/info.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide>
<ide> // print a warning if devicemapper is using a loopback file
<ide> if pair[0] == "Data loop file" {
<del> fmt.Fprintf(cli.err, " WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.")
<add> fmt.Fprintln(cli.err, " WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.")
<ide> }
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> // Only output these warnings if the server does not support these features
<ide> if info.OSType != "windows" {
<ide> if !info.MemoryLimit {
<del> fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No memory limit support")
<ide> }
<ide> if !info.SwapLimit {
<del> fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No swap limit support")
<ide> }
<ide> if !info.OomKillDisable {
<del> fmt.Fprintf(cli.err, "WARNING: No oom kill disable support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No oom kill disable support")
<ide> }
<ide> if !info.CPUCfsQuota {
<del> fmt.Fprintf(cli.err, "WARNING: No cpu cfs quota support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No cpu cfs quota support")
<ide> }
<ide> if !info.CPUCfsPeriod {
<del> fmt.Fprintf(cli.err, "WARNING: No cpu cfs period support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No cpu cfs period support")
<ide> }
<ide> if !info.CPUShares {
<del> fmt.Fprintf(cli.err, "WARNING: No cpu shares support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No cpu shares support")
<ide> }
<ide> if !info.CPUSet {
<del> fmt.Fprintf(cli.err, "WARNING: No cpuset support\n")
<add> fmt.Fprintln(cli.err, "WARNING: No cpuset support")
<ide> }
<ide> if !info.IPv4Forwarding {
<del> fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled\n")
<add> fmt.Fprintln(cli.err, "WARNING: IPv4 forwarding is disabled")
<ide> }
<ide> if !info.BridgeNfIptables {
<del> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-iptables is disabled\n")
<add> fmt.Fprintln(cli.err, "WARNING: bridge-nf-call-iptables is disabled")
<ide> }
<ide> if !info.BridgeNfIP6tables {
<del> fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-ip6tables is disabled\n")
<add> fmt.Fprintln(cli.err, "WARNING: bridge-nf-call-ip6tables is disabled")
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | remove unneeded code lines | 00a980825a658d32f89067f378471b5f46bade05 | <ide><path>lib/WebpackOptionsValidationError.js
<ide> const getSchemaPartText = (schemaPart, additionalPath) => {
<ide> return schemaText;
<ide> };
<ide>
<del>const getSchemaPartDescription = (schemaPart, additionalPath) => {
<del> if(additionalPath) {
<del> for(let i = 0; i < additionalPath.length; i++) {
<del> const inner = schemaPart[additionalPath[i]];
<del> if(inner)
<del> schemaPart = inner;
<del> }
<del> }
<add>const getSchemaPartDescription = schemaPart => {
<ide> while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
<ide> if(schemaPart.description)
<ide> return `\n-> ${schemaPart.description}`; | 1 |
Text | Text | fix usage example and separated into two example | 77137b1496d46dd515486ff651d9fd7c476a089a | <ide><path>guide/english/bash/bash-rm/index.md
<ide> title: Bash rm
<ide>
<ide> ## Bash command: rm
<ide>
<del>**Delete a File/Directory** ,for example `rm hello`.
<add>### Usage
<add>
<add>**Delete a File**
<add>
<add>```bash
<add>rm <file name or file path>
<add>```
<add>
<add>**Delete a Directory**
<add>
<add>```bash
<add>rm -R <folder name or folder path>
<add>```
<ide>
<ide> There are few commonly used arguments:
<ide> | 1 |
Mixed | Javascript | codify findsourcemap return value when not found | 72df448d2a896cbc8ab0d8a61b71b34da6582cec | <ide><path>doc/api/module.md
<ide> added:
<ide> -->
<ide>
<ide> * `path` {string}
<del>* Returns: {module.SourceMap}
<add>* Returns: {module.SourceMap|undefined} Returns `module.SourceMap` if a source
<add> map is found, `undefined` otherwise.
<ide>
<ide> `path` is the resolved path for the file for which a corresponding source map
<ide> should be fetched.
<ide><path>lib/internal/source_map/prepare_stack_trace.js
<ide> function getOriginalSource(payload, originalSourcePath) {
<ide>
<ide> function getSourceMapErrorSource(fileName, lineNumber, columnNumber) {
<ide> const sm = findSourceMap(fileName);
<del> if (sm === null) {
<add> if (sm === undefined) {
<ide> return;
<ide> }
<ide> const {
<ide><path>lib/internal/source_map/source_map_cache.js
<ide> function findSourceMap(sourceURL) {
<ide> if (sourceMap && sourceMap.data) {
<ide> return new SourceMap(sourceMap.data);
<ide> }
<del> return null;
<add> return undefined;
<ide> }
<ide>
<ide> module.exports = {
<ide><path>test/parallel/test-source-map-api.js
<ide> const { readFileSync } = require('fs');
<ide> );
<ide> }
<ide>
<add>// `findSourceMap()` should return undefined when no source map is found.
<add>{
<add> const files = [
<add> __filename,
<add> '',
<add> 'invalid-file',
<add> ];
<add> for (const file of files) {
<add> const sourceMap = findSourceMap(file);
<add> assert.strictEqual(sourceMap, undefined);
<add> }
<add>}
<add>
<ide> // findSourceMap() can lookup source-maps based on URIs, in the
<ide> // non-exceptional case.
<ide> { | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.